本文介绍了angular 4 不向服务器发送 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 withCredentials 时,我可以看到 cookie 被发送到服务器.但是都向服务器发送任何东西.我使用 laravel 作为后端,使用 angular 4 作为前端.此外,Chrome 开发人员工具上未显示 cookie,我无法使用它们访问它们.

When I use withCredentials I can see that cookies are sent to the server. But are send anything to the server. I use laravel as backend and angular 4 as frontend.also, the cookie not shown on chrome developer tools and I can't access them using.

此外,我在 laravel 中使用了 Cors 中间件,例如:

also, I used Cors middleware in laravel like:

<?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)
    {
      $response = $next($request);
      $response->headers->set('Access-Control-Allow-Origin', 'http://localhost:4200');
      $response->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
      $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Request-With');
      $response->headers->set('Access-Control-Expose-Headers', 'Content-Disposition, x-total-count, x-filename');
      $response->headers->set('Access-Control-Allow-Credentials', 'true');

      return $response;

    }
}

当我第一次向服务器请求设置 cookie 时,以下响应显示:

and when I request first time to the server for set cookie, these below response show:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Accept, Authorization, X-Request-With
Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin:http://localhost:4200
Access-Control-Expose-Headers:Content-Disposition, x-total-count, x-filename
Cache-Control:no-cache, private
Connection:keep-alive
Content-Type:application/json
Date:Tue, 02 Jan 2018 09:04:32 GMT
Server:nginx/1.11.9
Set-Cookie:refreshToken=def502005a2ccf60eafdee2137df25a628d49f70c4571bedde628d50e45c0fe4b73f84f86bb469f0f77247dc2abc13c0c5c938027beb13fe534eb7bb41f4aed99faf49ebf2a238a007ce9514108951366db45a311d70d17d65dd48f5df6aa50f257c828cce16e589983c1e06c9e8d7d52806a1a9401569f87b3a394469e938c4ddbfcc7985e257d8f0d0df416e7b8a5bbd19e86050db3be5b90953c515934f529489f4e0ba62fb66ab883d1689349bbfb962332bceb322d978b7d20fa7e32bb94eb0050d8f94bfd3a780c4edfeea8eaa6954222b57c30229c2494fec38ee5292396400b25fadee04cad1729f9e9b9ccf12d21a6ed3f9663d41c5423536e64f83542df19fcede28247bfc12accf354e035182c3e019e4a2b55c807924cc50a12fa187b2f655fb19c1b42a1ae526763dd08dbd0d288b3a9c649216ab1abc60cd51bb97dfb0cb7b7b020ff270cf5c81bc94f2acd40f92edeefaf585d46d0750bf; expires=Sun, 25-Aug-2019 09:04:32 GMT; Max-Age=51840000; path=/; HttpOnly
Transfer-Encoding:chunked
X-RateLimit-Limit:60
X-RateLimit-Remaining:58

当我从前端请求时:

refreshToken(){

const headers = new Headers({ 'Content-Type': 'application/json', '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);
      return response.json()
    },
  )
  .do(
    tokenData =>{
      localStorage.setItem('token', tokenData.access_token)
      localStorage.setItem('expires_in', tokenData.expires_in)
    }
  )
}

chrome 开发:

Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:Content-Type, Accept, Authorization, X-Request-With
Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin:http://localhost:4200
Access-Control-Expose-Headers:Content-Disposition, x-total-count, x-filename
Cache-Control:no-cache, private
Connection:keep-alive
Content-Type:application/json
Date:Tue, 02 Jan 2018 08:57:28 GMT
Server:nginx/1.11.9
Transfer-Encoding:chunked
X-RateLimit-Limit:60
X-RateLimit-Remaining:59

前后服务器使用不同的端口.

Front and back servers use different ports.

推荐答案

你可以保存 cookie,因为你的开发 node.js 服务器和你的 Laravel Vagrant box 在不同的域中.您可以做的是代理从 node.js 到 Laravel 服务器的调用.

You can's save cookies because your development node.js server and your Laravel Vagrant box are on different domains. What you can do is to proxy calls from node.js to the the Laravel server.

在 Angular 应用的根目录中创建 proxy.conf.json.在里面放一个带有路由的对象:

Create proxy.conf.json in the root of Angular app. Put an object with routes inside:

{
  "/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 并将 scripts 中的 start 的值更改为 ng serve --proxy-config proxy.conf.json.现在 npm run start 将从代理开始.我使用这个代理的问题是它将您的 URL (http://mydomian.test/) 解析为 IP.当它只用一个 IP 调用 Laravel 时,nginx 服务器不知道该怎么做,因为它必须接收一个域名.nginx 允许在同一个 IP 上有多个网站,因此它必须接收一个域名或拥有一个默认网站,它将所有没有域名的调用重定向到该网站.如果这在 Angular 的代理中仍未解决,请转到 Laravel 机器上的 /etc/nginx/sites-available,您将在那里拥有一个 mydomian.test 配置文件.它有 listen 80; 行,将其更改为 listen 80 default;.

I just have /api defined here because all my backend URIs are inside api.php. All calls that look like http://localhost:4200/api/someitems/1 will be proxied to http://mydomian.test/api/someitems/1.
Then edit package.json and change the value of start inside scripts to ng serve --proxy-config proxy.conf.json. Now npm run start will start with proxy. The problem I had with this proxy is that it resolves your URL (http://mydomian.test/) to an IP. When it calls Laravel with just an IP the nginx server does not know what to do because it must receive a domain name. nginx allows multiple website on the same IP so it must receive a domain name or to have a default website to which it redirects all calls those have no domain name. In case this is still not fixed in Angular's proxy go to /etc/nginx/sites-available on the Laravel machine, you'll have a mydomian.test config file there. It has listen 80; line there, change it to listen 80 default;.

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

Now you can change the API_DOMAIN variable to http://localhost:4200 (or remove it all together) and disable the CORS.

这篇关于angular 4 不向服务器发送 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:16