我有一个删除函数使用类型:"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('/');
});
}
应用.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设置为用户在 prompt(( 中输入的任何内容。康索洛尔上的错误是:
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)