我是node.js 和express.js 的新手。我正在尝试创建一个工作原理如下的待办事项应用程序: 我有一个包含单独待办事项列表的待办事项 mongodb。这些列表将任务分类为未完成或已完成。例如:
{
Todos: {
Todo: {
"_id" : ObjectId("5202b481d2184d390cbf6eca"),
finished: ['walk dog', 'do dishes'],
unfinished: ['clean room']
}
Todo: {
"_id" : ObjectId("5202b49ad2184d390cbf6ecb"),
finished: ['clean car', 'make dinner'],
unfinished: ['write this damn web app ']
}
}
}
我想为每个待办事项列表创建新页面,以便列表位于如下位置:http://website.com/5202b49ad2184d390cbf6ecb
所以我的问题是,如何才能像这样动态创建 URL?
谢谢!
编辑:
我将此代码添加到routes/index.js:
/* POST to New todo list service */
router.post('/:id', function(req, res) {
var db = req.db;
var tasks = db.get('taskscollection');
tasks.insert({
"id":req.params.id,
"finished":[""],
"unfinished":[""]
}, function(err, doc) {
if (err) {
res.send("there was a problem with adding a new tasklist");
}
else {
res.location("/:id");
res.redirect("/:id");
}
});
});
并将此代码添加到index.jade:
form#formNewTask(name='newtask', method='post', action='/:id')
button#btnSubmit(type="submit") New Task List
但是当我单击该按钮时,我被重定向到 localhost:3000/:id 并收到 404 not found。我在这里缺少什么?
另外,如何为新页面创建 Jade 模板?
编辑2:
我将 index.js 更改为如下所示:
/* POST to New todo list service */
router.post('/tasks/:_id', function(req, res) {
var db = req.db;
var tasks = db.get('taskscollection');
tasks.insert({
"finished":[""],
"unfinished":[""]
}, function(err, doc) {
if (err) {
res.send("there was a problem with adding a new task\
list");
}
else {
res.location("/tasks/"+req.params.id);
res.redirect("/tasks/"+req.params.id);
}
});
});
我的index.jade 现在有这个:
form#formNewTask(name='newtask', method='post', action='/tasks/'+_id)
button#btnSubmit(type="submit") New Task List
现在,当我单击新任务时,它会将我带到 localhost:3000/tasks/undefined。这是否表明它没有在数据库中创建新条目?我认为我的前端 Jade 文件是错误的,但我不确定。
最佳答案
app.get('/task/:id',
function(req,res){
//access the id by req.params.id
//and use it to obtain data from mongodb
});
当您发布数据时,对象尚未创建。因此没有_id。我的建议是在将新对象发布到数据库时不要使用参数,只需使用“/posttask/”之类的东西
app.post('/postnewtask/',...
并且您没有为“/task/:id”编写 get
调用。您只编写了一个 post
调用。
你得到的应该是
app.get('/task/:id'...
//use req.params.id and get data from database and render
关于javascript - Express.js 从 MongoDB ID 创建 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25052126/