【发布时间】:2017-12-12 02:14:59
【问题描述】:
我需要为我的 node.js express 项目找出正确的路线。我正在为培训师创建一个健康应用程序来管理他的客户。培训师可以访问个人客户资料并单击“任务列表”按钮访问他们的锻炼列表。在“练习列表”页面上,我需要能够将练习添加到其下方的列表中。
棘手的部分是将锻炼添加到该用户的锻炼列表的路由和 URL。
**tasks.js POST 问题所在,特别是重定向路由:重定向路由是否有可能?
----[[[[ res.redirect('user/' + _id + '/tasklist'); ]]]]
/* POST new exercise */
router.post('/user/:_id/tasklist/add', function(req, res, next){
var _id = req.params._id;
console.log("Add task for user id " + _id)
if (!req.user || !req.body || !req.body.text) {
//no task text info, redirect to home page with flash message
req.flash('error', 'please enter an exercise');
res.redirect('user/:_id/tasklist');
}
else {
// Insert into db. New tasks are assumed to be not completed.
var dateCreated = new Date();
// Create a new Task, an instance of the Task schema, and call save()
new Task( { user: _id , text: req.body.text, completed: false, dateCreated: new Date()} ).save()
.then((newTask) => {
console.log('The new exercise created is: ', newTask);
res.redirect('user/:_id/tasklist');
})
.catch((err) => {
next(err); // most likely to be db error.
});
}
});
** tasklist.hbs,顶部附近的 POST 添加按钮。需要仔细检查这里的路线和任务列表路线
<h1>EXERCISES</h1>
<div class="taskinfo">
<div class="addtask">
<form method="POST" action="/tasks/user/{{user.id}}/tasklist/add" class="add_form">
<input id="addtask_text" name="text" type="text" placeholder="Enter an exercise" required>
<input type="hidden" name="_id" value="{{user._id}}">
<input class="addtask_button" type="submit" value="ADD Exercise">
</form>
</div>
<div class="messages">
{{#if messages}}
<p class="error_msg">{{messages.error}}</p>
<p class="info_msg">{{messages.info}}</p>
{{/if}}
</div>
<div class="tasklist">
{{#each tasks}}
<p>{{@tasklist}}: <a href="/user/{{user.id}}/tasklist/{{this._id}}">{{this.text}}</a></p>
<form action="/user/{{user._id}}/tasklist/done" method="POST" class="done_form">
<input type="hidden" name="_id" value="{{this._id}}">
<input class="done_button" type="submit" name="done" value="Done">
</form>
<form action="/user/{{user._id}}/tasklist/delete" method="POST" class="delete_form">
<input type="hidden" name="_id" value="{{this._id}}">
<input class="delete_button" type="submit" name="done" value="Delete">
</form>
{{else}}
<p>There are no exercises. Time to create a list!</p>
{{/each}}
我收到 404 错误,因为新任务需要连接到用户的 ID 和他们的任务列表。这是我的 github 仓库:https://github.com/jhchiu1/healthapp
【问题讨论】:
-
那么,要从浏览器访问 tasklist.hbs 页面,url 看起来像 example.com/user/12345/tasklist 吗?
-
您好,感谢您的帮助!这是 404 页面的网址:127.0.0.1:3000/tasks/user//tasklist/add。在该 URL 中的“用户”和任务列表之间应该是数据库中该用户的用户 ID。
-
这是用户锻炼列表页面的网址:127.0.0.1:3000/user/5a2ed6db4455d101dec6f212/…
-
用户锻炼列表页面:127.0.0.1:3000/user/5a2ed6db4455d101dec6f212/…。此页面正在运行,因为任务列表已连接到该用户的 ID。我需要类似的东西才能将练习添加到该用户的任务列表中。
-
难怪你没有在你的
res.render()中传递user.id。在这种情况下,您的所有其他表单也必须具有user.idnull 。解决方案将在您的res.render()中传递user.id,或者从URL 字符串中获取。{{user._id}}怎么样?它们也为空吗?
标签: javascript html ruby-on-rails node.js express