JamieT
JamieT

Reputation: 1187

Adding a cookie to a HttpClient POST in Angular

Sorry if this is a duplicate, but I have not been able to find any solutions that have worked for me yet. My code works like this:

constructor(private _httpClient: HttpClient) {}


login(){

    var cookieToAdd = getCookie();
    var token = getToken();

    this._httpClient
        .post("https://myApi/login", { username: "myUsername", pw: "myPw", token: token }, { cookieToAdd })
        .subscribe((result: any) => {
            // do stuff here
        });

}

So obviously the last parameter in the post is incorrect, but I hope you see the point. I wish to make this post request with a cookie I have obtained from a previous api call, but I cannot find how to add a cookie to a post request using Angulars HttpClient. The endpoint returns an error if the cookie is not present. I have received my desired output from the endpoint using Postman, but cannot replicate adding the cookie properly in code. Any help would be greatly appreciated.

edit:

I have also tried something like: 

var myHeaders = new HttpHeaders({'Set-Cookie': 'CookieName='+cookieToAdd'});
this._httpClient
        .post("https://myApi/login", { username: "myUsername", pw: "myPw", token: token }, { headers: myHeaders })
        .subscribe((result: any) => {
            // do stuff here
        });

Upvotes: 0

Views: 1198

Answers (1)

Hien Nguyen
Hien Nguyen

Reputation: 18965

You can pass cookie as a property of input object and check logic in your login function API

this._httpClient
        .post("https://myApi/login", { username: "myUsername", pw: "myPw", token: token, cookie: cookievalue }

Upvotes: 0

Related Questions