Solvedangular HttpClient.post body param is not sent correctly when using 'application/x-www-form-urlencoded' content type request header
✔️Accepted Answer
If i do it like that, it works fine for me.
`
const body = new HttpParams()
.set('client_id', Settings.client_id)
.set('client_secret', Settings.client_secret)
.set('grant_type', 'password')
.set('scope', Settings.scope)
.set('username', auth.username)
.set('password', auth.password);
return this.http.post(Settings.iam_service_base_url + 'connect/token', body.toString(), {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
})
`
Other Answers:
Hello @TitaneBoy,
I agree with some of the other commenters here - you cannot use application/x-www-form-urlencoded
as your Content-Type
and send a JSON encoded body. This is essentially lying to the server, and telling it to parse the body using a different format from the one it's actually encoded in.
What's happening is that your server-side framework is interpreting the JSON string as one long parameter name, with an empty value. Either encode your body in application/x-www-form-urlencoded
format (pass an HttpParams
instance as the body), or use application/json
.
Why do you JSON.stringify
the object?
I have the same problem with Angular 4.4.4
@fk-mbc
I've just removed the "next()" instruction in my ".options" function and It works well now (with 'application/json' content type only...)
Web-client page
Client-Side
Server-side
It can be a workaround for now but overall, it is not working at all with 'application/x-www-form-urlencoded' content type header. I will rename the title of this issue to make focus of this aspect
I'm submitting a...
Current behavior
When sending http post request (using HttpClient) with body data (for example a json object), it looks that Angular send the json object as a "key" of another object.
For example, when doing
this.httpClient.post('https://localhost/login', JSON.stringify({username, password})
, if username is equal to (for example) 'user' and password is equal to 'pass', the request object in the server side will contain a body value like this:{{"username": "user", "password": "pass"}:""}
Here is a screenshot of what we can see as the value of "body" in request object, in server-side,
As you can see, the body object I'm trying to send with HttpClient.post seems to be the "key" of another Object wrapped around it, with an empty value..But it should be an object
Expected behavior
Angular should send body object as an object, and not as the key of another object
Minimal reproduction of the problem with instructions
Here is the code of my authentication service:
In the server side, I'm using Node.js (v8.4.0) with Express (v4.16.0)
Environment
Thank you in advance for your help