laravel5.5 cors has been blocked by CORS policy: Request header field x-csrf-token is not allowed by

文章目录

      • 场景
      • 参考文档
        • 分析
      • 解决

场景

  • laravel5.5 一个项目的接口给另外一个项目B使用,所以需要解决跨域的问题
    • 定义了api group的middleware CorsMiddleware, 项目B的控制台观察到
      • has been blocked by CORS policy: Request header field x-csrf-token is not allowed by Access-Control-Allow-Headers in preflight response.

参考文档

  • HTTP 访问控制

分析

  • Access-Control-Allow-Headers 首部字段用于预检请求的响应。其指明了实际请求中允许携带的首部字段。
    • Access-Control-Allow-Headers: [, ]*
  • CorsMiddleware中设置x-csrf-token到预检header允许传递的字段
    • 观察了下项目B的预检请求 x-requested-with也是需要传递的字段,所以一起添加了

解决

  • 设置Access-Control-Allow-Headers


namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        return $next($request)->header('Access-Control-Allow-Origin', 'https://learn.carsonlius.vip')
            ->header('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS,PATCH,DELETE,HEAD')
            ->header('Access-Control-Allow-Headers', 'x-csrf-token,x-requested-with');
    }
}

你可能感兴趣的:(http,php,laravel)