我在 glitch.me 上写了一个小的 node.js 应用程序,我遇到了一个我不太明白的问题。它有点像留言板(freeCodeCamp 的项目),您可以在其中发布主题(指定留言板),然后查看留言板上的消息列表。线程存储在 mongodb 集合中。板的名称通过 req.params.board
访问。问题是,req.params.board
以某种方式在两次函数调用之间缩短了 1 个符号。
这是我的路由文件和我的处理程序(在单独的模块中),在处理程序中有 console.logs 会告诉你我的意思。假设我们在“newBoard”板上创建了一个帖子:
API.js
module.exports = function (app) {
app.route('/api/threads/:board')
.get(threadHandler.getThreads)
.post(threadHandler.postThread)
.delete(threadHandler.deleteThread)
.put(threadHandler.reportThread)
app.route('/api/replies/:board')
.post(threadHandler.postReply)
.get(threadHandler.getReplies)
.delete(threadHandler.deleteReply)
.put(threadHandler.reportReply)
};
处理程序:
module.exports.postThread = function(req, res){
console.log(req.params.board); //logs newBoard
var newThread = new Thread({
text: req.body.text,
delete_password: req.body.delete_password,
created_on: new Date(),
bumped_on: new Date(),
reported: false,
replies: [],
replycount: 0,
board: req.params.board
})
newThread.save();
res.redirect('/b/'+req.params.board);
}
module.exports.getThreads = function(req, res){
//gets 10 last messages on the board
console.log(req.params.board); //logs newBoar
Thread.find({}).sort({bumped_on: -1}).limit(10).exec(function (err, docs){
if (err) return;
docs.forEach(function(doc)
{
if(doc.replies.length > 3) {
doc.replies = doc.replies.slice(-3);
}
})
res.json(docs);
})
}
module.exports.getReplies = function(req, res){
//gets a separate thread with all the replies
console.log(req.params.board, 'reply'); //logs newBoard + _id of the thread, so the url is '/newBoard/5900d2da926ef6277e143564' it will log '/newBoard5900d2da926ef6277e143564', 'eating' the slash between board and id.
Thread.findById(req.query.thread_id, function(err, foundThread){
if (err) return;
if (foundThread){
res.json(foundThread);
}
})
}
我不明白发生了什么,所以如果有人告诉我为什么会发生这种情况以及如何解决它,我将不胜感激。我的整个项目在这里:https://glitch.com/edit/#!/shrouded-consonant
最佳答案
您正在重定向到 /b/newBoard
,但是 your HTML这样做:
var currentBoard = window.location.pathname.slice(3,-1);
它假定重定向完成到/b/newBoard/
;对于 -1
,它试图分割不存在的尾部斜线。因此 newBoar
。
最简单的解决方案是修复重定向:
res.redirect('/b/' + req.params.board + '/');
关于javascript - req.params 调用之间的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43640830/