HttpClient POST request using x-www-form-urlencoded

I am trying to make a POST request with the header x-www-form-urlencoded 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 an empty username and password.

so I decided to make a postman request to my endpoint entry and see where this problem came from, and the postman request returned a username and password.

How is it that when I send mail from a mailbox, my API returns my username and password, and when I send a message from my Angular application, my API returns empty values? Is there something I am missing?

+11
source share
2 answers

You send JSON data to the API instead of the form data. Below is a snippet below.

 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') } ); } 
+25
source

You can make a mail request as shown below.

 login(email:string, password:string):Observable<User>{ let headers = new HttpHeaders(); headers = headers.set('Content-Type', 'application/x-www-form-urlencoded') let params = new HttpParams().set('user', JSON.stringify({email: email,password:password})); return this.http.post<User>(`${MEAT_API_AUX}/login`, {},{headers: headers,params:params}) .do(user => this.user = user); } 

after that you need to subscribe.

-3
source

Source: https://habr.com/ru/post/1273440/


All Articles