写在前面:vue + PHP +laravel
最近小编在写前端接口的时候,遇到了跨域问题。
报错如下:
解决思路:
在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, ];
在web.php中调用中间件即可;
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