When I execute the following code from my browser the server gives me 400 and complains that the request body is missing. Anybody got a clue about how I can pass a simple string and have it send as the request body?
let content = 'Hello world'
axios.put(url, content).then(response => {
resolve(response.data.content)
}, response => {
this.handleEditError(response)
})
If I wrap content in [] it comes thru. But then the server receives it as a string beginning with [ and ending with ]. Which seems odd.
After fiddling around I discovered that the following works
let req = {
url,
method: 'PUT',
data: content
}
axios(req).then(response => {
resolve(response.data.content)
}, response => {
this.handleEditError(response)
})
But shouldn't the first one work as well?
Sending a PUT Request with Axios The simplest way to make the PUT call is to simply use the put() function of the axios instance, and supply the body of that request in the form of a JavaScript object: const res = await axios. put('/api/article/123', { title: 'Making PUT Requests with Axios', status: 'published' });
So yes, a PUT request, technically, strictly, has to have a body.
The Content-Type request header indicates the media type of the PUT request body, and the Content-Length request header indicates the data size in the PUT request message. In this PUT Request Example, we send JSON to the ReqBin echo URL. Click Send to execute the PUT request online and see the results.
I solved this by overriding the default Content-Type:
const config = { headers: {'Content-Type': 'application/json'} }; axios.put(url, content, config).then(response => { ... });
Based on my experience, the default Conent-Type
is application/x-www-form-urlencoded
for strings, and application/json
for objects (including arrays). Your server probably expects JSON.
This works for me (code called from node js repl):
const axios = require("axios"); axios .put( "http://localhost:4000/api/token", "mytoken", {headers: {"Content-Type": "text/plain"}} ) .then(r => console.log(r.status)) .catch(e => console.log(e));
Logs: 200
And this is my request handler (I am using restify):
function handleToken(req, res) { if(typeof req.body === "string" && req.body.length > 3) { res.send(200); } else { res.send(400); } }
Content-Type header is important here.
I was having trouble sending plain text and found that I needed to surround the body's value with double quotes:
const request = axios.put(url, "\"" + values.guid + "\"", {
headers: {
"Accept": "application/json",
"Content-type": "application/json",
"Authorization": "Bearer " + sessionStorage.getItem('jwt')
}
})
My webapi server method signature is this:
public IActionResult UpdateModelGuid([FromRoute] string guid, [FromBody] string newGuid)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With