【问题标题】:Angular 2 cookie not set未设置 Angular 2 cookie
【发布时间】:2017-08-27 06:20:53
【问题描述】:

我是这样使用http的:

private headers = new Headers({ 'Content-Type': 'application/json' })
login(loginUser: LoginUser): Promise<User> {
        return this.http.post('http://localhost:9009/api/users/login', JSON.stringify(loginUser), { headers: this.headers })
            .toPromise()
            .then(res => res.json())
            .catch(this.handleError)
    }

这应该会自动设置cookie到浏览器,像这样:

但是浏览器中没有设置cookie。

  • Angular 版本:2.4.10
  • 浏览器:Chrome 56.0.2924.87(64 位)| FireFox 52.0.2(64 位)
  • 语言:TypeScript 2.2.1
  • 节点(针对 AoT 问题):node --version = 3.10.10

响应头:

【问题讨论】:

  • 没有烤饼干。
  • 谢谢,我通过设置 withCredentials=true 解决了这个问题

标签: angular http cookies


【解决方案1】:

我参考以下资源解决了我的问题:

首先,这是关于 Cross-origin 的问题。我必须在我的 java 服务器(在过滤器中)设置 CORS 标头,如下所示:

    httpServletResponse.addHeader("Access-Control-Allow-Origin", "http://localhost:4444");
    httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
    httpServletResponse.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
    httpServletResponse.addHeader("Access-Control-Max-Age", "3600");
    httpServletResponse.addHeader("Access-Control-Allow-Headers", "Content-Type, Range");
    httpServletResponse.addHeader("Access-Control-Expose-Headers", "Accept-Ranges, Content-Encoding, Content-Length, Content-Range");

其次,我在提出请求时设置了withCredentials 属性,如下所示:

get(url: string, parmas: any): Observable<any> {
    return this.http.get(url, { search: parmas, headers: this.headers, withCredentials: true })
        .map((res: Response) => res.json())
        .do(data => console.log('server data:', data))  // debug
        .catch(this.handleError);
}

最后,感谢@JJJ 帮助我检测我的拼写错误。

【讨论】:

    【解决方案2】:
    1. 客户端应具有 withCredentials: true 选项以将 cookie 传递到后端 api,并且 CORS 配置应具有“Access-Control-Allow-Credentials”、“true”

    2. 如果在不同主机浏览器中创建的cookie不会从前端传递cookie(cookie创建主机和客户端URL主机地址应该匹配)

    3. 除了 cookie 之外,CORS 将用于配置允许的标头、主机和 http 方法

    4. 浏览器在发出实际请求之前会调用 OPTIONS,因此如果使用 api 网关,则应配置预流(例如:apigee)

    【讨论】:

      猜你喜欢
      • 2021-08-15
      • 2020-04-04
      • 2017-08-21
      • 2020-10-21
      • 2017-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      相关资源
      最近更新 更多