0

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

2
  • No cookie baked. Commented Apr 2, 2017 at 9:33
  • Thanks,I solved it by setting withCredentials=true Commented Apr 2, 2017 at 12:38

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.