When I make a PUT request from the frontend, I am currently using the XMLHttpRequest and FormData
API. However, on the server side, I am not receiving any data such as
req.params, req.body, and req.query
are all empty.
Front-end Implementation
var reportSub = () => {
var report = document.getElementById('report');
var formData = new FormData(report)
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.response)
}
}
var queryString = new URLSearchParams(formData);
xhr.open("PUT", '/threads/edit', true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data');
xhr.send(queryString)
}
var reportsub = document.querySelector('#repsub');
reportsub.addEventListener("click",(e)=>{
e.preventDefault();
reportSub();
})
Server-side Code
router.put('/threads/edit',(req,res)=>{
let board = req.body.board;
let id = req.body.id;
console.log(req.query,req.body)
Board.findById({_id: ObjectId(id)},(error,data)=>{
if(error)
res.send(error)
if(data!==null){
data.Reprot = true;
data.save((error,sd)=>{
if(error)
res.send(error)
res.send(sd);
})
}
else{
res.send({"Error":"Id does not exist "})
}
})
})
One possible solution is to hard code the data in the URL for each variable that needs to be passed, which is not ideal. That's why I prefer using the FormData interface to send data.