lite-server 的 Angular2 不附加自定义 headers 或 cookie

Angular2 with lite-server does not attach custom headers or cookies

我在 localhost:8080 上有一个 REST 后端 运行ning,它会在用户登录时发出一个 cookie。我有一个与后端打包在一起的 Angular2 前端。当我 运行 项目时,angular 发送 cookie 并将自定义 header 附加到后端请求。但是,当我 运行 前端使用列表服务器之一 localhost:3000 时,angular 不发送任何 cookie 并且不附加自定义 header.

请求时 运行 后端:

Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Cookie:io=8Dk6ajOQZyDz-bvXAAAB; jwt=eyJh...H1aCccT2U
Host:localhost:8080
Referer:http://localhost:8080/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36
X-CSRF-Token:2c8744ff-38ad-49cb-bf07-fe75cd16f827

运行 lite-server 和 apache2

Accept:*/*
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:x-csrf-token
Access-Control-Request-Method:GET
Connection:keep-alive
Host:localhost:8080
Origin:http://localhost:3000
Referer:http://localhost:3000/
User-Agent:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36

据我了解,cookie 不是特定于端口的,因此应该与来自 localhost:3000 和 localhost:8080 的请求一起发送。

我在后端有一个 CORS 过滤器来接受来自任何来源的所有请求。

  1. 为什么 header 没有被附加?
  2. 为什么没有附加 cookie?

此问题与 lite-server 无关。每当您 运行 在与 back-end 不同的 port/domain 上使用 front-end 时,您将需要明确允许某些行为发生,例如设置 cookie 或允许 header待读。

要让 back-end 设置的 cookie 存储在浏览器中,angular 请求必须与 withCredentials 一起发送,其中附加了以下 header请求。

Access-Control-Allow-Credentials:true

this.http.post(this.loginUrl,
        JSON.stringify({ username: username, password: password }),
        {headers: this.headers, withCredentials: true})...

我设置了一个 HTTP 服务包装器,将其附加到每个请求。

为了 angular 读取 back-end 发送的自定义 header,CORS 需要发送以下内容 header:

Access-Control-Expose-Headers:X-CUSTOM-HEADER

才会暴露给angular。希望这对某人有所帮助。