如何在 NodeJS 中创建具有唯一 ID 的路由

How to create routes with unique ids in NodeJS

所以我正在用节点、快递、猫鼬和 mongodb 开发一个项目。我能够 create/save 数据库的主题。但是当主题是 saved/created 时,我想将用户重定向到该创建主题的主题详细信息页面(所以基本上每个创建的主题都有自己独特的 url 基于 id,就像这样 -> localhost:3000/topicdetail/id)

我的问题是,在重定向时我收到一条错误消息:错误:无法在视图目录“/Users/Grace/Desktop/QA/views”

中查找视图 "error"

所以我的主要问题是我是用它自己的唯一 ID 正确地重定向它还是我做错了什么。欢迎任何帮助。

我的代码如下:

var mongoose = require('mongoose');
var Topic = require('../models/topic');
var db = require('../config/database');
var express = require('express');
var router = express.Router();

// render the start/create a new topic view
router.get('/', function(req, res) {
  res.render('newtopic');
});

// save topic to db
router.post('/',function(req, res, next){
console.log('The post was submitted'); 

var topic = new Topic
({
    "topicTitle":       req.body.topicTitle,
    "topicDescription": req.body.topicDescription,
    "fbId":             req.body.userIdFB,
    "twId":             req.body.userIdTW
})

topic.save(function (err, topic)
{
    if(err){
        return next(err)
        console.log('Failed to save the topic to the database');
    }
    else
    {
        console.log('Saved the topic succesfully to the database');
        // each topic has its own unique url 
        res.redirect('/topicdetail/{id}');
    }
})

});

module.exports = 路由器;

调用 res.redirect('/topicdetail/{id}'); 不会插入任何 ID。 Express 不会重新格式化字符串。它采用您定义的重定向,在本例中为 /topicdetail/{id} 并执行它。就像您将其插入浏览器一样。

要重定向您的详细视图,您可以执行以下操作: res.redirect('/topicdetail/' + topic._id); 并将 topic.id 替换为您的文档 ID 或其他标识符。

提醒一下:您的详细路线在路线定义中需要一个参数。示例:app.get('/verification/:token', users);:token 是您的参数。更多关于 routing guide.