【发布时间】:2017-08-13 11:19:17
【问题描述】:
我正在尝试使用 jQuery 向我的服务器发送一个 Ajax PUT 请求,但是当我 console.log 通过我的成功函数返回的数据时,我得到的数据与我尝试更新的数据完全相同。
这是我的 Ajax 请求:
$(".plus-button").on("click", function() {
var handler = $(this).siblings(".editIngredientForm");
var formData = {
photoName: handler.children("#numberOfItems").prevObject[0][0]["value"],
name: handler.children("#numberOfItems").prevObject[0][1]["value"],
// Add + 1 to number of items in ingredient to account for the clicking on plus sign
number: Number(handler.children("#numberOfItems").prevObject[0][2]["value"]) + 1,
};
var actionUrl = $(this).siblings(".editIngredientForm").attr("action");
// console.log(formData);
$.ajax({
url: actionUrl,
data: formData,
type: "PUT",
success: function(data) {
console.log(data);
}
})
});
这是处理更新的后端路由(Node JS):
app.put("/inventory/:id", isLoggedIn, function(req, res) {
Ingredient.findByIdAndUpdate(req.params.id, req.body.item, { new: true }, function(err, updatedIngredient) {
if (err) {
console.log(err);
} else {
if (req.xhr) {
res.json(updatedIngredient);
} else {
req.flash("success", "You successfully updated the Ingredient's info");
res.redirect("/inventory/" + req.params.id);
}
}
})
})
有谁知道我做错了什么?
【问题讨论】:
-
req.body.item有值吗? -
确保你已经安装了body-parser并配置了中间件app.use(body.json());
-
我不知道 node.js,但我看不到您将返回值更改为更新值的位置。
-
@RolandStarke 当我在 else{ 之后 console.log(req.body.item) 时,什么都没有打印出来。
-
@santoshsingh Body-parser 已安装,我添加了 app.use(bodyParser.json()),但它仍然不起作用。