Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient POST request using x-www-form-urlencoded

Tags:

angular

I'm trying to make a POST request with x-www-form-urlencodedcontent type header as follows:

login(username, password): Observable<any> {     return this.http.post('/login', {       username: username,       password: password       },       {         headers: new HttpHeaders()           .set('Content-Type', 'x-www-form-urlencoded')       }       ); 

Unfortunately my API says that I sent empty username and password.

so I decided to make a postman request to my login endpoint and see where the problem comes from, and the postman request did return the username and password.

How comes that when I'm posting from postman my API return my username and password and when I post from my Angular app my API returns empty values? Is there anything I'm missing?

like image 648
TheUnreal Avatar asked Oct 12 '17 16:10

TheUnreal


People also ask

How do I send application X www form Urlencoded in HttpClient?

In order to send the data in x-www-form-urlencoded format, we can use FormUrlEncodedContent class. It accepts the data as an IEnumerable of KeyValue pairs. var data = new[] { new KeyValuePair<string, string>("name", "John Doe"), new KeyValuePair<string, string>("email", "[email protected]"), };

How send POST request with X www form Urlencoded body android?

openConnection(); connection. setRequestMethod("POST"); connection. setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection. setRequestProperty("Content-Length", "" + Integer.

What does HttpClient post return?

The HttpClient. post() returns Observable instance of given response type. On this page we will see injecting HttpClient , creating request body and passing HTTP options. We will also look into error handling. For the demo we will use Angular In-Memory Web API to post data.


1 Answers

You're posting JSON data to the API instead of form data. The snippet below should work.

login(username, password): Observable<any> {   const body = new HttpParams()     .set('username', username)     .set('password', password);    return this.http.post('/login',     body.toString(),     {       headers: new HttpHeaders()         .set('Content-Type', 'application/x-www-form-urlencoded')     }   ); } 
like image 118
Owain van Brakel Avatar answered Sep 24 '22 03:09

Owain van Brakel