Laravel 5.5 和 Angular 4 设置 cookie

Laravel 5.5 and Angular 4 set cookie

我使用 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时,它不起作用!我用了 angular 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

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

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

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

我只是在这里定义了 /api,因为我所有的后端 URI 都在 api.php 中。所有看起来像 http://localhost:4200/api/someitems/1 will be proxied to http://mydomian.test/api/someitems/1 的调用。 然后编辑 package.json 并将 start inside scripts 的值更改为 ng serve --proxy-config proxy.conf.json。现在 npm 运行 start 将使用代理启动。我使用此代理时遇到的问题是它将您的 URL (http://mydomian.test/) 解析为 IP。当它只用一个 IP 调用 Laravel 时,nginx 服务器不知道该怎么做,因为它必须接收一个域名。 nginx 允许同一 IP 上的多个网站,因此它必须接收一个域名或有一个默认网站,它将所有没有域名的调用重定向到该默认网站。如果 Angular 的代理仍未修复此问题,请转至 Laravel 机器上的 /etc/nginx/sites-available,您将在那里获得一个 mydomian.test 配置文件。它有听80;在那一行,将其更改为默认监听 80;.

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