ws2823147532
ws2823147532

Reputation: 31

Angular 2 cookie not set

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.

The response headers:

Response headers

Upvotes: 0

Views: 4027

Answers (2)

Thofiq
Thofiq

Reputation: 49

  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)

Upvotes: 0

ws2823147532
ws2823147532

Reputation: 31

I solved my problem referring to the following resources:

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.

Upvotes: 3

Related Questions