我一直在遵循一个使用mongoDB、Express、JQuery和Node.js构建CRUD应用程序的教程。我现在正在尝试添加自定义功能,但当我偏离我模仿的代码时,无法同时编辑和检索文档。我很好奇发生了什么事。我遵循了有效的删除和编辑功能,建立了一个新的编辑功能,允许我更新多个字段和一个不同的UI。我还想让文档使用字段来填充在网站的不同部分的不同块的HTML,但我无法让文档返回。
我已经保证get和put函数在Postman中工作正常。
这就是它的工作原理:
app.put('/:id',(req,res) =>{
const todoID = req.params.id;
const userInput = req.body;
db.getDB().collection(collection).findOneAndUpdate({_id:
db.getPrimaryKey(todoID)}, {$set: {todo: userInput.todo}},
{returnOriginal : false},(err,result)=>{
if(err)
console.log(err);
else{
res.json(result);
}
});
});
app.post('/',(req,res)=>{
const userInput = req.body;
db.getDB().collection(collection).insertOne(userInput,
(err,result)=>{
if(err)
console.log(err);
else
res.json({result: result, document: result.ops[0]});
});
});
app.delete('/:id',(req,res)=>{
const todoID = req.params.id;
db.getDB().collection(collection).findOneAndDelete({_id :
db.getPrimaryKey(todoID)},(err,result)=>{
if(err)
console.log(err);
else
res.json(result);
});
});
这个可以在postman中运行,但不能在我的应用程序中运行:
app.get('/', (req,res)=>{
const todoID = req.params.id;
db.getDB().collection(collection).findOne({_id:
db.getPrimaryKey(todoID)}, (err,documents)=>{
if(err)
console.log(err);
else{
console.log(documents);
res.json(documents);
}
});
});
这是有效的:
const deleteShipment = (shipment, divShipmentID, deleteID) =>{
let deleteBtn = $(`#${deleteID}`);
deleteBtn.click(()=>{
fetch(`/${shipment._id}`,{
method: "delete"
}).then((response)=>{
return response.json();
}).then((data)=>{
if(data.ok == 1){
$(`#${divShipmentID}`).remove();
}
});
});
}
这不是:
const openEditOptions = (shipment, editID) =>{
let editBtn = $(`#${editID}`);
editBtn.click(()=>{
console.log('activated');
fetch(`/${shipment._id}`,{method: "get"}).then((response)=>{
return response.json();
}).then((data)=>{
console.log(data);
readyEditForm(shipment);
});
});
}
这是HTML:
<button class="shipment-edit" id="edit_5c6759a05b4290e978136ea0"
type="button">Edit</button>
<button type="button" class="shipment-delete"
id="delete_5c6759a05b4290e978136ea0">Delete</button>
我期望该特定“装运”的编辑按钮在被点击后会记录到控制台“激活”,并在控制台和函数readyEditForm中返回装运数据。什么都没发生。
发布于 2019-02-16 11:28:39
req.params
是在路径中的:
之后获取路由参数的方法。
app.get('/:id' (req, res) => {
console.log(req.params.id); //prints whatever the user put in place of ":id"
});
app.get('/' (req, res) => {
console.log(req.params.id); //prints undefined
});
一旦你修复了这部分代码,剩下的部分就应该可以工作了。
https://stackoverflow.com/questions/54719428
复制相似问题