Axios Http client - How to construct Http Post url with form params
Why pull in another library or module to do something so simple with pure vanilla JavaScript? It's really one line of JS to produce the desired data to submit in your POST request.
// es6 example
const params = {
format: 'json',
option: 'value'
};
const data = Object.keys(params)
.map((key) => `${key}=${encodeURIComponent(params[key])}`)
.join('&');
console.log(data);
// => format=json&option=value
const options = {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data,
url: 'https://whatever.com/api',
};
const response = await axios(options); // wrap in async function
console.log(response);
You have to do the following:
var querystring = require('querystring');
//...
axios.post(authServerUrl + token_access_path,
querystring.stringify({
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}), {
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function(response) {
console.log(response);
});
If your target runtime supports it, Axios is able to accept a URLSearchParams
instance which will also set the appropriate Content-type
header to application/x-www-form-urlencoded
axios.post(authServerUrl + token_access_path, new URLSearchParams({
username: 'abcd', //gave the values directly for testing
password: '1235!',
client_id: 'user-client'
}))
The same goes for the fetch
API
fetch(url, {
method: "POST",
body: new URLSearchParams({
your: "object",
props: "go here"
})
})