简体   繁体   中英

Javascript if not in dictionary (node.js)

Here's the code:

exports.index_post = function(req, res) {
  var nicks = [];
  if (req.body.nick) {
    for (var nick in nicks) {
      if (nick == req.body.nick) {
        res.redirect("/");
      } else {
        nicks.push(req.body.nick)
        req.session.nick = req.body.nick;
        res.redirect("/msg");
        console.log(nicks);
      }
    }
  } else {
    res.redirect("/");
  }
};

What it's meant to do is check if req.body.nick is one of the items in the nicks dictionary, and if if is redirect it back to the root. If it's not in the dictionary, it should add it to the dictionary and set it as a session variable, then redirect to /msg. However, this code doesn't seem to be working for me and instead it causes Express to hang. Could someone tell me what I'm doing wrong? Thanks.

First off, you're creating a new nicks array every time the function is run; it sounds like you want this to persist throughout the life of the server, each request potentially adding to the nicks array. Also, though you're iterating over the array looking for req.body.nick , the way the if/else statement is written inside the loop, it will always redirect on the very first iteration through the loop. Try something like this:

var nicks = []; // don't reset `nicks` every call

exports.index_post = function(req, res) {
  if (req.body.nick) {
    if (nicks.indexOf(req.body.nick) != -1) { // better checking for nick in nicks
      res.redirect("/");
    } else {
      nicks.push(req.body.nick)
      req.session.nick = req.body.nick;
      res.redirect("/msg");
      console.log(nicks);
    }
  } else {
    res.redirect("/");
  }
};
  1. Your nicks is empty

    so your for loop won't do anything

    you don't even have a chance to push anything into it

  2. For each request you'll have a new nicks , it's not global

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM