Post a number as a JSON
See original GitHub issueHello,
When posting an object or array with axios, axios automatically sets the request content type to ‘application/json’, which is the common use case for APIs nowadays.
According to the README, “By default, axios serializes JavaScript objects to JSON.”.
And according to the official JSON specification’s right sidebar, a valid JSON stream can also be a primitive value (null, a boolean, a number or a string).
But axios.post(url, 42)
will not send the request as content-type=‘application/json’, but as ‘application/x-www-form-urlencoded’.
For now, in our project, we are setting the content-type as ‘application/json’ manually when sending numbers or other primitives, and our server is able to parse this JSON without any explicit declaration.
Wouldn’t it be better for axios to do this by default, as numbers are valid JSON, and axios states that it sends JSON by default?
I didn’t file this as a feature request or a bug, as it may be intentional. Or if it is not intentional, it may be difficult to change that behavior, as it would introduce a breaking change.
Best regards, Sébastien.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:7 (1 by maintainers)
Top GitHub Comments
There are certainly use cases for this; it’s perfectly valid to send primitives as JSON body. I just encountered the same problem.
As for the urgency; it is not that urgent as there is a workaround in available and it is a breaking change; however, according to the docs, axios should (by default) encode objects to JSON. This is obviously broken for primitive objects, and leads to unexpected behavior.
In fact, the concept to switch to application/x-www-form-urlencoded by simply using qs.stringify() is logically flawed, as it contradicts the default encoding to JSON for strings. I think this is a design flaw that should be adressed prior to releasing a 1.0.0.
that’s part of the default
transformRequest
, looks like it was on purpose, set the content-type asapplication/x-www-form-urlencoded
, from ourdefaults.js
. It’s weird as you mention that it’s set to form-urlencoded, if we make the change it would have to be on the 1.0.0 release, since this is a breaking change for some use cases. Doesn’t seem urgent unless you can describe a use case for this, we have a few things to fix before this one. Thanks for looking into this!