Context: I am trying to send a put request to a server using JavaScript and fetch from an html file I'm writing.
Problem: The request I made is working in Insomnia, but when I try to send it from an html it isn't properly received. The code was generated by Insomnia also. When I send it from the html the request is sent, and I get an ok back, but the server doesn't complete the task in the request, leading me to believe that it wasn't received or I missed something. When trying to send the request, the console shows a response, that says "ok", 200, etc., but also has a "bodyUsed: false" part.
The function generated by Insomnia:
fetch("url", {
"method": "PUT",
"headers": {
"content-type": "application/x-www-form-urlencoded"
},
"body": {
"name": "name",
"desc": "description"
}
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});
Question(s): Is there anything wrong with the code? How does the server receive the request but not the body? Does the "bodyUsed: false" message mean that the request's body was ignored for some reason? Could this all be the server's fault?
Disclaimer: I am a bit new to web development, so forgive me if I miss some obvious point.
If you keep "content-type": "application/x-www-form-urlencoded"
and your server is configured that way, you should send your data using a FormData like this:
var formData = new FormData();
formData.append('name', 'Chris');
formData.append('descr', 'description');
fetch("url", {
"method": "PUT",
"headers": {
"content-type": "application/x-www-form-urlencoded"
},
"body": formData
})
.then(response => {
console.log(response);
})
.catch(err => {
console.log(err);
});