Munchkin
Munchkin

Reputation: 1085

Express.js UnhandledPromiseRejectionWarning: Unhandled promise rejection

So I have the following code:

app.post('/api/login', async function (req, res){
  try  {
    let [sorted,users] = await getSorted();
    const pw = req.body.password;
    const submittedUser = req.body.username;
    const hashedPassword = await bcrypt.hash(req.body.password, 10);
    // const user = { id: req.body.id, username: req.body.username, password: req.body.password };
    // USERNAME = FIRSTNAME
    var user = new User({firstname: req.body.username, eMail: req.body.eMail, password: hashedPassword });
    sorted.forEach(async ([firstname, password]) => {
      let result = bcrypt.compareSync(pw, password);
      // r = true if hash = hashed pw
      var serializeCookie = function(key, value, hrs) {
        // This is res.cookie’s code without the array management and also ignores signed cookies.
        if ('number' == typeof value) value = val.toString();
        if ('object' == typeof value) value = JSON.stringify(val);
        return cookie.serialize(key, value, { expires: new Date(Date.now() + 1000 * 60 * hrs), httpOnly: true });
      }; 

      var setMultipleCookies = function(res) {
        set_cookies.push(getCookie(access_token, myValue1.toString(), default_cookie_age));
        set_cookies.push(getCookie(loggedinid, myValue2.toString(), default_cookie_age));
        res.header("Set-Cookie", set_cookies);
      } 
      set_cookies = ['loggedinid', id]
      if (result === true && firstname == submittedUser) {
        jwt2.sign({user}, 'secrethere', { expiresIn: '15min'}, (err, token) =>{
          set_cookies.push('access_token'+ 'Bearer'+token).header("Set-Cookie", set_cookies)
                     .json(user);
        });
      }
      else {
        res.status(200).send("bad login");
      } 
    });    
  } catch (err) {
    res.status(500).send();
    console.log(err);
  }
});

Error I am getting thrown out:

(node:6628) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:6628) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

What I am trying to accomplish:

My login function, which definitely worked before needed some pimping in order to set multiple cookies. I found a question here on SO, which I can't find anymore, which stated that there's a bug and some comments that maybe it's fixed, but found no evidence of that since the code just did not work. So I had to do this hack, which I implemented in my code and it gave me these errors. set_cookies = ['loggedinid', id] should get the second cookie as key loggedinid and value variable id. Id is the MongoDB ID name

Upvotes: 0

Views: 1053

Answers (1)

trincot
trincot

Reputation: 351338

At least these issues:

  1. There is no await anywhere in the forEach callback, so marking that callback as async has no purpose. Drop that keyword, and you'll not get that unhandled promise rejection any more. Change:

    sorted.forEach(async ([firstname, password]) => {
    

    To:

    sorted.forEach(([firstname, password]) => {
    
  2. The following statement references an non-existing header property:

    set_cookies.push('access_token'+ 'Bearer'+token).header("Set-Cookie", set_cookies)
               .json(user);
    

    The return value of push is an integer, so you cannot call .header() on that. That triggers an exception. Maybe you intended to call .header() on res:

    set_cookies.push('access_token'+ 'Bearer'+token);
    res.header("Set-Cookie", set_cookies)
       .json(user);
    
  3. You have an undefined variable id in this line:

    set_cookies = ['loggedinid', id]
    

    I cannot really say what you intended here, but you should make sure that id has been defined and has the appropriate value

  4. The variable val in serializeCookie is never defined. Possibly you intended value.

There are still other issues unrelated to your question, such as:

  1. The two functions serializeCookie and setMultipleCookies are never called.

  2. If you do intend to use serializeCookie, then it is quite inconsistent in how it writes data. There really should not be any type-checking if there. It should just always do:

    value = JSON.stringify(value);
    

    The function could just be:

    var serializeCookie = function(key, value, hrs) {
        return cookie.serialize(key, JSON.stringify(value), 
               { expires: new Date(Date.now() + 1000 * 60 * hrs), httpOnly: true });
    }; 
    

Upvotes: 2

Related Questions