【发布时间】:2018-12-21 12:40:41
【问题描述】:
所以我得到了这个 JavaScript,它应该使用 ajax 向我的服务器发送一些带有 PUT 的数据。
var payload = 'id=' + id + '&brand=' + brand + '&model=' + model + '&country=' + country + '&number=' + number + '&alkohol=' + alkohol + '&volume=' + volume + '&price=' + price + '&comment=' + comment;
var fixedPayload = payload.split(' ').join('+'); // replace blanks with +
$.ajax({
type: 'PUT',
url: 'http://localhost:3000/drinks/' + fixedPayload,
// data: fixedPayload, this does not work either
success: function (data) {
alert('Update was successfull!');
}
});
这是在服务器上
app.put('drinks/:id', (req, res) => {
let id = req.params.id;
var data = {
brand: req.body.brand,
model: req.body.model,
country: req.body.country,
number: req.body.number,
alkohol: req.body.alkohol,
volume: req.body.volume,
price: req.body.price,
comment: req.body.comment
};
Drink.findByIdAndUpdate(id, data, function(err, drink) {
if (err) throw err;
res.send('Drink updated - '+drink.model);
});
});
这就是我得到的
jquery-3.3.1.min.js:2 PUT http://localhost:3000/drinks/?5c1b873a6a0a5d3ae0342f01&brand=L%C3%A4sk&model=Cola&country=Sverige&number=999&alkohol=0%&volume=33+cl&price=20&comment=Cola+asd 404(未找到)
Console.log(fixedPayload)
?5c1b873a6a0a5d3ae0342f01&brand=Läsk&model=Cola&country=Sverige&number=999&alkohol=0%&volume=33+cl&price=20&comment=Cola+asd
似乎是什么问题? 我也尝试发送一个对象而不是一个字符串,但结果相同
解决了
AJAX
package = {
brand: brand,
model: model,
country: country,
number: number,
alkohol: alkohol,
volume: volume,
price: price,
comment: comment
};
$.ajax({
type: 'PUT',
url: `http://localhost:3000/drinks/${id}`, // changed it here
data: package,
success: function (data) {
alert('Update was successfull!');
window.location = "http://localhost:3000/";
}
});
【问题讨论】:
-
你的 url contanis / before ?.
-
固定示例是(手动)进行表单编码。也许动态版本正在发送 JSON,但服务器应该是表单编码?
-
另外,您引用的输出显示 404 状态(未找到),但标题显示 400(错误请求):这是什么? (它们确实意味着不同的东西。)
-
也许将
headers: {'content-type': 'application/json'}添加到jquery.ajax? -
是的,我开始摆弄代码,var payload = '?' + id + '&brand'... 给出 404
标签: javascript node.js ajax express bad-request