Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2.0 Http post request does not send credentials

Tags:

angular

Api works perfectly when called from advanced client rest but when I called through http it doesn't work as expected. This is because it is not sending the credentials. Guys help me how can I use here withCredentials:true.

Here is my angular code :

var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
this.http.post('http://localhost/jiffy_fun/laravel/public/token',{headers: headers}).map(res => res.json()).subscribe(res => {this.token = res});

Thanks

like image 536
vikram mistry Avatar asked Jul 17 '26 06:07

vikram mistry


1 Answers

I think that you mix two different things. For what I saw in the code you provided, you want to send credentials from a form using an AJAX request using Angular2 HTTP class. In this case, you need to provide this content within the second parameter of the post method, as described below:

var creds = "username=" + username + "&password=" + password;

var headers = new Headers();
headers.append('Content-Type',
         'application/x-www-form-urlencoded');
this.http.post(
    'http://localhost/jiffy_fun/laravel/public/token',
    creds,
    {headers: headers})
.map(res => res.json())
.subscribe(res => {this.token = res});

The withCredentials attribute is something different related to CORS (cross domain requests). In fact, by default, CORS doesn't send cookies for such requests. You can choose to change this behavior by setting the withCredentials attribute to true on the xhr object. This link could give you some additional hints: http://www.html5rocks.com/en/tutorials/cors/?redirect_from_locale=fr. See this withCredentials section.

Hope it helps you, Thierry

like image 111
Thierry Templier Avatar answered Jul 19 '26 21:07

Thierry Templier