Laravel CORS错误与凭证

时间:2017-12-31 07:52:50

标签: angular laravel api cors laravel-5.5

我使用角4作为前端和laravel(homestead mydomain.test)作为后端。 当我想将cookie从angular 4发送到laravel API后端时,Chrome浏览器中显示以下错误:

barryvdh / laravel-cors配置文件(cors.php配置文件):

return [

    /*
    |--------------------------------------------------------------------------
    | Laravel CORS
    |--------------------------------------------------------------------------
    |
    | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
    | to accept any value.
    |
    */

    'supportsCredentials' => true,
'allowedOrigins' => ['http://localhost:4200'],
'allowedHeaders' => ['Content-Type','Accept'],
'allowedMethods' => ['GET','POST','PUT', 'PATCH', 'OPTION'],
'exposedHeaders' => ['Content-Disposition', 'x-total-count', 'x-filename', '*'],
'maxAge' => 0,
'hosts' => ['*'],

棱角4请求:

refreshToken(){

    const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': 'Bearer ' + this.getToken()})
    let options = new RequestOptions({ headers: headers, withCredentials: true });
    return this.http.post(API_DOMAIN + 'refresh', JSON.stringify({}), options)
      .map(
        (response) => {
          console.log(response.json());
          return response.json()
        },
      )
  }

浏览器错误:

Failed to load http://mydomian.test/api/refresh: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

2 个答案:

答案 0 :(得分:0)

你不需要任何laravel cors。只需将此代码放入.htaccess文件中

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Credentials true
Header add Access-Control-Allow-Headers "authorization,language,Content-Type"
Header add Access-Control-Allow-Methods "GET,POST,OPTIONS,DELETE,PUT"

答案 1 :(得分:0)

我通过以下方式解决了这个问题: 在Angular应用程序的根目录中创建proxy.conf.json。放置一个包含路径的对象:

{
  "/api": {
    "target": "http://mydomian.test/",
    "secure": false
  }
}

我在这里定义了/ api,因为我的所有后端URI都在api.php中。所有看起来像http://localhost:4200/api/someitems/1的来电都将代理到http://mydomian.test/api/someitems/1。 然后编辑package.json并将脚本内的start值更改为ng serve --proxy-config proxy.conf.json。现在npm run start将以proxy开头。我对此代理的问题是它将您的URL(http://mydomian.test/)解析为IP。当它仅使用IP调用Laravel时,nginx服务器不知道该怎么做,因为它必须接收域名。 nginx允许同一IP上的多个网站,因此它必须接收域名或拥有一个默认网站,它重定向所有没有域名的呼叫。如果仍然没有在Angular的代理中修复,请转到Laravel机器上的/ etc / nginx / sites-,你可以在那里找到一个mydomian.test配置文件。它有听80;在那里,改变它听80默认;。

现在,您可以将API_DOMAIN变量更改为http://localhost:4200(或将其全部删除)并禁用CORS。