Node.js 使用Axios将React的请求提交给mongodb
我需要一些帮助。当我使用Axios从React应用程序发送PUT请求时,该请求不起作用。但当我测试Postman提供的api时,它的工作方式与预期的一样。服务器端-节点+mongoose+mongodbNode.js 使用Axios将React的请求提交给mongodb,node.js,reactjs,mongodb,api,axios,Node.js,Reactjs,Mongodb,Api,Axios,我需要一些帮助。当我使用Axios从React应用程序发送PUT请求时,该请求不起作用。但当我测试Postman提供的api时,它的工作方式与预期的一样。服务器端-节点+mongoose+mongodb modifyCurrentHaspInfo = (e) => { if (prompt("Enter password:") === "123456") { axios.put("/hasp/change", { data: {
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!");
}
}
当它找到正确的id时,必须更改正文中的数据。以下是来自服务器的代码:
//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);
}
});
});
这是因为您的axios格式不正确(而不是您在后端所期望的) 您现在从axios发送数据的方式可以通过以下方式在后端访问:
req.body.data
// which will be an object like
{
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
}
因此可以像req.body.data.\u id
一样访问\u id
。将您的请求更改为以下内容之一(注意差异)
或
axios.put("/hasp/change", {
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
})
axios.put({
url: "/hasp/change",
data: {
_id: "5cd40f6f1e922c236caa82f4",
serial: "11111-22222",
soft: "test-put"
}
})