Wednesday, 26 April 2017

req.params changes between calls

I am writing a small node.js app on glitch.me and I have run into problem I don't really understand. It's kind of a message board (a project for freeCodeCamp), where you can post a thread (specifiyng a board) and then see the list of messages on the board. Threads are stored in mongodb collection. The name of the board is accessed through req.params.board. The problem is, req.params.board somehow gets 1 symbol shorter between two function calls. Here are my routing file and my handlers (in a separate module), and in handlers there are console.logs that will show you what I mean. Let's say we create a post on 'newBoard' board:

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)

};

hadnlers:

  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);
    }
  })
}

I don't understand what's happening, so I'd be really grateful if somebody told me why does it happen and how to fix it. My whole project is here: https://glitch.com/edit/#!/shrouded-consonant



via Enk

No comments:

Post a Comment