写在前面:Vue + PHP +laravel 最近小编在写前端接口的时候,遇到了跨域问题。 报错如下: 解决思路: 在app\Http\Middleware 下创建Crosshttp.php配置文件;
最近小编在写前端接口的时候,遇到了跨域问题。
报错如下:
解决思路:
在app\Http\Middleware 下创建Crosshttp.php配置文件;
server('HTTP_ORIGIN') ? $request->server('HTTP_ORIGIN') : ''; $allow_origin = [ 'http://localhost:3000', ]; if (in_array($origin, $allow_origin)) { $response->header('Access-Control-Allow-Origin', $origin); $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Cookie,X-Requested-With, X-CSRF-TOKEN, Accept, Authorization, X-XSRF-TOKEN'); $response->header('Access-Control-Expose-Headers', 'Authorization, authenticated'); $response->header('Access-Control-Allow-Methods', 'GET, POST, PATCH, PUT, OPTIONS'); $response->header('Access-Control-Allow-Credentials', 'true'); } return $response; }}
在Kernel.php中添加
在 producted $middleGroups api中加入cors;
protected $middlewareGroups = [ 'web' => [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' => [ 'throttle:60,1', 'bindings', 'cors' ], ];
在 protected $routeMiddleware 中引入cors
protected $routeMiddleware = [ 'auth' => \App\Http\Middleware\Authenticate::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class, 'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class, 'can' => \Illuminate\Auth\Middleware\Authorize::class, 'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class, 'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class, 'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class, 'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class, 'checklogin' => \App\Http\Middleware\IsLogin::class, 'getnotice' => \App\Http\Middleware\getNotice::class, 'getprivs' => \App\Http\Middleware\getPrivs::class, 'cors'=>\App\Http\Middleware\CrossHttp::class, ];
Route::group(['middleware'=>['cors']],function() { Route::get('/news/getfirst', 'NewsController@getFirst'); });
前端也要设置header允许跨域访问:'Access-Control-Allow-Origin': '*'
headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'multipart/fORM-data', 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', }
最后,记得要清缓存哦~
另外,如上所时候配置好后如果还是提示跨域问题,不妨检查下接口路由是否完整,接口代码是否能正常访问,通常接口报错也会提示跨域问题的,今天的分享就到这里~~
来源地址:https://blog.csdn.net/weixin_44707364/article/details/126278918
--结束END--
本文标题: Laravel处理跨域问题
本文链接: https://lsjlt.com/news/429148.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0