I'm trying to make a POST request with x-www-form-urlencoded
content 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?
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]"), };
openConnection(); connection. setRequestMethod("POST"); connection. setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection. setRequestProperty("Content-Length", "" + Integer.
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.
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') } ); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With