2017-04-26 27 views
1

我在glitch.me上寫了一個小型的node.js應用程序,並遇到了我不太瞭解的問題。這是一種留言板(一個freeCodeCamp項目),您可以在其中發佈一個線程(指定一個板),然後在板上查看消息列表。線程存儲在mongodb集合中。董事會的名稱通過req.params.board訪問。問題是,req.params.board以某種方式在兩個函數調用之間縮短1個符號。 這裏是我的路由文件和我的處理程序(在一個單獨的模塊中),在處理程序中有console.logs,它們會告訴你我的意思。比方說,我們創建'newBoard的董事會後:req.params調用之間的變化

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

回答

3

您將會重定向到/b/newBoard,但your HTML做到這一點:

var currentBoard = window.location.pathname.slice(3,-1); 

它假定重定向是爲了/b/newBoard/;與-1,它試圖切片不存在的尾部斜線。因此newBoar

最簡單的解決方法是修復重定向:

res.redirect('/b/' + req.params.board + '/'); 
+0

非常感謝!重定向原來只是問題的一部分,所以我改變了切片HTML以使其更加萬無一失(在這種情況下,傻瓜就是我自己)。 – Enk