Angular 2 cookie not set

纵然是瞬间 提交于 2020-06-03 10:01:10

问题


I use the http like this:

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)
    }

This should set cookie to browser automatically, like this:

Console screenshot

But there is no cookie set in browser.

  • Angular version: 2.4.10
  • Browser: Chrome 56.0.2924.87 (64-bit) | FireFox 52.0.2 (64-bit)
  • Language: TypeScript 2.2.1
  • Node (for AoT issues): node --version = 3.10.10

The response headers:

Response headers


回答1:


I solved my problem referring to the following resources:

  • Understanding and using CORS
  • How to fix CORS problems

First, this is a problem about Cross-origin.I must set CORS Headers at my java server(in the filter),like this:

    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");

Second, I set the withCredentials attribution when I make request,like this:

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);
}

Last, thanks @JJJ for helping me detecting of my spell errors.




回答2:


  1. Client should have withCredentials: true option to pass cookies to back end api and CORS config should have "Access-Control-Allow-Credentials", "true"

  2. If cookie created in different host browser will not pass cookie from front end (cookie creation host and client URL host address should match)

  3. CORS will be used to configure allowed headers, host and http methods apart from cookie

  4. Browser makes OPTIONS call before making actual request so if using api gateway should have preflow configured (ex: apigee)



来源:https://stackoverflow.com/questions/43166754/angular-2-cookie-not-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!