Reputation: 301
I need some little help. PUT request doesn't work when I send it from React app using Axios. But when I test PUT api from Postman - it works as it suppose to. Server side - node+mongoose+mongodb.
modifyCurrentHaspInfo = (e) => {
if (prompt("Enter password:") === "123456") {
axios.put("/hasp/change", {
data: {
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
}
})
.then((res) => {
console.log(res.data);
})
.catch((err) => {
console.log(err);
})
} else {
alert("Wrong password!");
}
}
When it finds correct id - data in body must be changed. Here is code from server:
//PUT request
app.put("/hasp/change", function(req, res) {
//console.log(req.body);
HaspInfo.findOneAndUpdate({_id: req.body._id}, {$set:req.body}, {new: true}, function(err, hasps) {
if (err) {
res.status(500).send({error: "Could not modify hasp info..."});
} else {
//console.log(hasps);
res.status(200).send(hasps);
}
});
});
Upvotes: 1
Views: 3235
Reputation: 6718
It's because your axios is malformed (not what you're expecting at the backend).
The way you're sending data now from axios can be accessed at the backend as
req.body.data
// which will be an object like
{
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
}
So _id
can be accessed like req.body.data._id
. Change your request to one of the following (note the differences)
axios.put("/hasp/change", {
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
})
Or
axios.put({
url: "/hasp/change",
data: {
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
}
})
Upvotes: 1