CORS:预检响应中的Access-Control-Allow-Header不允许使用Content-Type

时间:2016-10-10 16:35:49

标签: javascript php cors vue.js lumen

我使用vuejs和流明为api构建应用程序,

我的vuejs应用在尝试验证时发出错误

XMLHttpRequest无法加载http://api.dev/auth/login。请求标题字段在预检响应中,Access-Control-Allow-Headers不允许使用Content-Type。

我有一些中间件来处理角色

class cors {

    /**
     * @var array
     */
     protected $settings = [
      'maxAge'            => 0,
      'origin'            => '*',
      'allowMethods'      => '*',
      'exposeHeaders'     => '*',
      'allowedHeaders'    => '*'
     ];

public function handle(ServerRequestInterface $request, Closure $next)
{
   //handle preflight request
    if ('OPTIONS' == $request->getMethod()) {
        $response =  new \Illuminate\Http\Response('',"204");
        $this->setOrigin($request, $response);
        $this->setAllowHeaders($request,$response);
        return $response;
    }
}

/**
 * @param ServerRequestInterface $request
 * @param ResponseInterface $response
 */
protected function setOrigin(ServerRequestInterface $request,$response)
{
    $origin = $this->settings['origin'];
    if (is_callable($origin)) {
        $origin = call_user_func($origin,$response->withAddedHeader('Origin',$origin));
    }
    $response->headers->set('Access-Control-Allow-Origin', $origin);
}

/**
 * @param ServerRequestInterface $request
 * @param ResponseInterface $response
 */
protected function setAllowHeaders(ServerRequestInterface $request,$response)
{
    if (isset($this->settings['allowedHeaders'])) {
        $allowedHeaders = $this->settings['allowedHeaders'];
        if (is_array($allowedHeaders)) {
            $allowedHeaders = implode(", ", $allowedHeaders);
        }
    }
    else { 
        $allowedHeaders = $request->hasHeader("Access-Control-Request-Headers");
    }

    if (isset($allowedHeaders)) {
        $response->headers->set('Access-Control-Allow-Headers', $allowedHeaders);
    }
}
}

在Chrome中,我的回复标题显示

Access-Control-Allow-Headers:*
Access-Control-Allow-Origin:*
Cache-Control:no-cache
Content-Type:text/html; charset=UTF-8
Date:Mon, 10 Oct 2016 16:10:52 GMT
Server:Caddy
Status:204 No Content
X-Powered-By:PHP/7.0.10

如果我设置了一个通配符Access-Control-Allow-Headers,为什么它不接受标题?

1 个答案:

答案 0 :(得分:1)

根据answer to this questionAccess-Control-Allow-Headers的通配符相对较新(2016年5月),因此大多数浏览器可能没有广泛采用。

您应该准确定义要在预检请求中允许的标题。