PUT Requests with Axios
The easiest way to make a PUT request with Axios is the
axios.put()
function. The first
parameter to axios.put()
is the URL, and the 2nd
is the HTTP request body.
const res = await axios.put('https://httpbin.org/put', { hello: 'world' });
res.data.json; // { hello: 'world' }
By default, if the 2nd parameter to axios.put()
is an object, Axios
serializes the object to JSON using the JSON.stringify()
function.
If the 2nd parameter is an object, Axios also sets the content-type
header to application/json
, so
most web frameworks, like Express, will be able
to automatically convert the request body into a JavaScript object for you.
const res = await axios.put('https://httpbin.org/put', { hello: 'world' });
res.data.headers['Content-Type']; // application/json;charset=utf-8
Form-Encoded Request Bodies
If you pass a string as the body
parameter to axios.put()
, Axios will
set the content-type
header to application/x-www-form-urlencoded
.
That means the request body should be a bunch of key/value pairs separated by
&
, like key1=value1&key2=value2
.
const res = await axios.put('https://httpbin.org/put', 'hello=world');
res.data.form; // { hello: 'world' }
res.data.headers['Content-Type']; // application/x-www-form-urlencoded