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

所以我正在与节点,快车,mongoose和蒙古的工作。 我能够创build/保存主题到数据库。 但是当主题被保存/创build时,我想将用户redirect到创build的主题的主题详细信息页面(因此,基本上每个创build的主题都有自己独特的基于id的URL,例如 – > localhost:3000 / topicdetail / id )

我的问题是,redirect时,我得到一个错误说:错误:无法查看视图“错误”视图目录“/用户/宽限期/桌面/质量保证/视图”

所以我的主要问题是我是否正确地redirect它自己的唯一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 = router;

调用res.redirect('/topicdetail/{id}'); 不会插入任何ID。 Express不会重新格式化string。 它需要您的定义redirect,在这种情况下/topicdetail/{id}并执行它。 就像你将它插入浏览器一样。

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

提醒一下:您的详细路线在路线定义中需要一个参数。 例如: app.get('/verification/:token', users);:token是你的参数。 关于路由指南的更多信息。