CORS middlware在预检OPTIONS请求上运行,但不在主要请求上运行

时间:2016-12-06 09:54:36

标签: php laravel api http-headers middleware

我已经创建了一个处理我的CORS请求的中间件:

    <?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
      $headers = [
           'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
           'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization',
           'Access-Control-Allow-Origin' => '*'
       ];

     $response = $next($request);
     foreach ($headers as $key => $value){
       $response->headers->set($key, $value);
      }
     return $response;
    }
}

我已将其添加到我的kernel.php

'api' => [
        'throttle:60,1',
        'bindings',
        'cors'
    ],

当我向GET提出/user请求时,一切正常,但当我向POST发出/api/answers请求时,我收到了一条CORS错误:{{1} }。两者都在我的XMLHttpRequest cannot load http://localhost:8000/api/answers. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

api.php

1 个答案:

答案 0 :(得分:0)

如果您尚未将中间件定义为路由中间件

,请使用类引用
'api' => [
        'throttle:60,1',
        'bindings',
        App\Http\Middleware\Cors::class
    ],