suhaotian / xior

A lite request lib based on fetch with plugin support and similar API to axios.
https://suhaotian.github.io/xior/
MIT License
193 stars 4 forks source link

POST with URI encoded data instead of JSON #26

Closed guoyunhe closed 3 months ago

guoyunhe commented 4 months ago

There are some really old back-end systems that don't support JSON API. Instead, they support encoded URI data as body.

axios supports a usage like this:

axios.post('/foobar', new URLSearchParams({
  foo: 'bar',
}));

axios will automatically set content-type header to application/x-www-form-urlencoded;charset=UTF-8;

However, xior doesn't seem to support this. When I write:

xior.post('/foobar', new URLSearchParams({
  foo: 'bar',
}));

xior will send a request with no content-type header, and back-end will reject it.

I can fix my code by manually adding the missing header. But maybe it makes sense that xior can do this automatically for users.

suhaotian commented 4 months ago

Good catch! 👊👍 I will enhance it in next version.


Currently, there is a better way to do that:

import xior from 'xior';

xior.defaults.headers['content-type'] = `application/x-www-form-urlencoded`;

xior.post('/foobar', {foo: 'bar', bar: {a: 1}}); // and support nested object encoding
suhaotian commented 4 months ago

Fixed in v0.5.4 🥳 now support:

xior.post('/', new URLSearchParams({foo: 'bar'}))