问题
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:

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:

回答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:
Client should have withCredentials: true option to pass cookies to back end api and CORS config should have "Access-Control-Allow-Credentials", "true"
If cookie created in different host browser will not pass cookie from front end (cookie creation host and client URL host address should match)
CORS will be used to configure allowed headers, host and http methods apart from cookie
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