我有一些未答复的发布,我有一个样本crud Vuejs与Axios如下:
updateItem: function () {
var obj = {'name': this.name, 'dob': this.dob, 'gender': this.gender}
// console.log(obj)
var strngObj = qs.stringify(obj)
this.axios.put('http://localhost:3000/crud/update/', this.update_id,
strngObj, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
// emulateJSON: true // fix cannot post as form data and urlencoded
).then((resp) => {
if (resp.data.log === 'update success !') {
this.items.push(resp.data.data)
alert(resp.data.log)
}
console.log(resp.data) // check full object in browser console log
})
},
以下代码是服务器端
app.put('/crud/update/:UPid', (rqs, rsp, next) => {
rqs.header("Access-Control-Allow-Origin", "*");
rqs.header("Access-Control-Allow-Methods", "POST,PUT");
var obj = { "_id" : mongodb.ObjectID(rqs.params.UPid) };
var update = { $set : { name: rqs.body.name, dob: rqs.body.dob, gender:
rqs.body.gender} }; // $set is object
var cursor = db.collection('info').updateMany(obj,update, function(err, res)
{
if (err) throw err;
rsp.send({log: "update success !",data: obj});
console.log(rqs.body);
// console.log(update);
//db.close();
});
})
我在chrome上进行了测试和调试。用于创建和阅读工作正常但更新(PUT方法),删除(DELETE)根本不起作用,它总是显示错误:
204无内容
谢天谢地!
答案 0 :(得分:1)
您正确编写更新工作的代码,204状态意味着您需要将后端(nodejs代码)的响应返回到您的前端(vuejs)
你需要将json对象从nodejs api返回到vuejs,这意味着
nodejs代码将如下:
app.put('/crud/update/:UPid', (rqs, rsp, next) => {
`rqs.header("Access-Control-Allow-Origin", "*");
rqs.header("Access-Control-Allow-Methods", "POST,PUT");`
`var obj = { "_id" : mongodb.ObjectID(rqs.params.UPid) };
var update = { $set : { name: rqs.body.name, dob: rqs.body.dob, gender: `
` rqs.body.gender} }; // $set is object
var cursor = db.collection('info').updateMany(obj,update, function(err, res)
{
if (err) throw err;
//delete this line
// rsp.send({log: "update success !",data: obj});
console.log(rqs.body);
//add this line to return json object
rsp.json({ status: "success"});
});
})`
,你的vuejs更新方法将是:
` updateItem: function () {
var obj = {'name': this.name, 'dob': this.dob, 'gender': this.gender}
// console.log(obj)
var strngObj = qs.stringify(obj)
this.axios.put('http://localhost:3000/crud/update/', this.update_id,
strngObj, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
// emulateJSON: true // fix cannot post as form data and urlencoded
).then((resp) => {
// parse json object response
var status = JSON.parse( resp.data.status);
}).catch(e => {
this.errors.push(e);
})
},`