我有一个删除函数使用类型:'DELETE'这种方式,我现在正在尝试创建一个UPDATE函数,虽然我不知道我是否正确这样做,目前的代码如下:
EJS:
<a href="#" class="editEvent" data-id="<%= event._id %>">Edit</a></p>
JS:
$(document).ready(function(){
$('.editEvent').on('click', editEvent);
});
function editEvent(){
var change = prompt('Change to:', '');
$.ajax({
type:'UPDATE',
url: '/events/update/'+$(this).data('id'),
data: change
}).done(function(response){
window.location.replace('/');
});
}
app.js:
app.post('/events/update/:id', function(req,res){
db.events.update({_id: ObjectId(req.params.id)}, {$set: {event_name: data}},function(err, result){
if(err){
console.log(err);
}
res.redirect('/');
});
});
所以我想使用$ set在MongoDB中更新,并将event_name设置为提示符()中用户输入的内容。 consolole的错误是:
UPDATE http://localhost:3030/events/update/5a959fdb9effb926a0594d90 400 (Bad Request)
正如Kevin已经指出的那样,你需要在客户端和服务器端将你的动作动词从UPDATE
更改为PUT
。
在服务器端,您需要访问通过ajax请求发送的用户输入。如果您已安装bodyparser
中间件,则可通过req.body
使用。
你也重定向两次。
//client.js
$(document).ready(function(){
$('.editEvent').on('click', editEvent);
});
function editEvent(){
var change = prompt('Change to:', '');
$.ajax({
type:'PUT',
url: '/events/update/'+$(this).data('id'),
data: {event_name: change}
}).done(function(response){
console.log(response);
window.location.replace('http://localhost:3030/');
}).fail(function(response){
console.log("Oops not working");
});
}
//app.js
app.put('/events/update/:id', function(req,res){
const data = req.body;
db.events.update({_id: ObjectId(req.params.id)}, {$set: data},function(err, result){
if(err){
console.log(err);
}
res.send('updated successfully');
});
});
请尝试将您的$.ajax({ type:'UPDATE'
更改为$.ajax({ type:'PUT'
并将app.post('/events/update/:id', function(req,res)
更改为app.put('/events/update/:id', function(req,res)