Laravel 5.5和Angular 4设置cookie

时间:2017-12-30 09:05:37

标签: php angular cookies laravel-5 homestead

我使用laravel作为后端(在homestead实现 - mydomain.test)和angular 4作为前端(在http://localhost:4200实现),现在,我想设置一个从后端到前端浏览器的cookie。

后端控制器:

return response(['access_token'=>$response['access_token'], 'expires_in' => $response['expires_in']])
          ->withCookie($cookie);

并且回复是:

Access-Control-Allow-Origin:*
Cache-Control:no-cache, private
Connection:keep-alive
Content-Type:application/json
Date:Sat, 30 Dec 2017 09:01:11 GMT
Server:nginx/1.11.9
Set-Cookie:refreshToken=def50200b16fb4563dfa726245a813985f300394fcce058b32138d85d62791e53869049c4dc71358e5789fb267457313e295f43b4f8dc8a5c4a22b03577ef77fb114f71fe17dbad637fc07105cbc67f58adbc905008fb870eae6b238047c9037fdbcf2710909538b36f8432f9528d52c9afd8774fe68ebfb11d125f0951b69ede08e164a1b0f1fe1510906a30858cb1946868a7d89d2d289b27140155b4fca33bee35ce9560696e023a484412bbbf26751ca81d96c88879c6a885b0ed72cc0b0c63639df38b3f7170561c559570cd5fa8faeec89ce06ddaf073a4634dcd5d49c0c5500dc63aeec5d5ffa99c2bad4c817f454c3bfa228397f18162e6fce64790da2f138a506bc906ae944a9aee29f1aa2b49bf2189d703706b2f475588f819985ad6942312070f5c887eec3deaa0761157f3cd86f0a016f3b19a311223c9b703a89efdfd96a878330b4e7dc86b0759c91be9bd7905ed6b94fec3587528402b7; expires=Thu, 22-Aug-2019 09:01:11 GMT; Max-Age=51840000; path=/; HttpOnly
Transfer-Encoding:chunked
Vary:Origin
X-RateLimit-Limit:60
X-RateLimit-Remaining:59

但是当我想将cookie从前端发送到后端时,它不起作用!我使用了角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()
    },
  )
}

和后端方:

$refreshToken = $request->cookie(self::REFRESH_TOKEN);
var_dump($refreshToken); // to be null always

你能帮我解决这些问题吗?

1 个答案:

答案 0 :(得分: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。