我使用 MERN 堆栈(Mongo、Express、React、Node)编写了一个简单的“杂货清单”Web 应用程序。我遇到的问题是除非我重新加载页面,否则我的 DELETE REST 命令不会触发。下面是我的事件处理程序和后端的源代码。
事件处理程序
handleRemove(e) {
fetch('http://localhost:3001/list/' + e._id, {
headers: {
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json"
},
method: "DELETE",
body: e
})
this.refs.list.forceUpdate();
}
快速后端
router.delete('/list' +'/:id',function(req,res) {
item.remove({
_id: req.params.id
}, function(err) {
if(err) {
res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "PATCH, POST, GET, PUT, DELETE, OPTIONS");
res.header("Access-Control-Allow-Methods", "POST, GET, DELETE");
res.header("Access-Control-Allow-Credentials", "true");
return res.send(err);
} else {
console.log("successfully deleted")
}
})
})
点击
<button onClick={() =>
this.props.handleRemove(item)}
className="item" key={item._id + "btn"}>Remove</button>