簡體   English   中英

Express.js UnhandledPromiseRejectionWarning: 未處理的 promise 拒絕

[英]Express.js UnhandledPromiseRejectionWarning: Unhandled promise rejection

所以我有以下代碼:

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

我被拋出的錯誤:

(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.

我要完成的工作:

我的登錄名 function,在需要一些拉皮條以設置多個 cookies 之前肯定可以工作。 我在 SO 上發現了一個問題,我再也找不到了,它指出存在一個錯誤和一些可能已修復的評論,但由於代碼不起作用,因此沒有發現任何證據。 所以我不得不做這個黑客,我在我的代碼中實現了它,它給了我這些錯誤。 set_cookies = ['loggedinid', id]應該獲取第二個 cookie 作為鍵 loggedinid 和值變量 id。 Id 是 MongoDB ID 名稱

至少這些問題:

  1. forEach回調中的任何地方都沒有await ,因此將該回調標記為async沒有任何意義。 刪除該關鍵字,您將不會再收到未處理的 promise 拒絕。 改變:

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

    至:

     sorted.forEach(([firstname, password]) => {
  2. 以下語句引用了一個不存在的header屬性:

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

    push的返回值是 integer,所以你不能調用.header() 這會觸發異常。 也許您打算在res上調用.header()

     set_cookies.push('access_token'+ 'Bearer'+token); res.header("Set-Cookie", set_cookies).json(user);
  3. 您在此行中有一個未定義的變量id

     set_cookies = ['loggedinid', id]

    我不能真正說出你在這里的意圖,但你應該確保id已定義並具有適當的值

  4. serializeCookie中的變量val從未定義。 可能你的預期value

還有其他與您的問題無關的問題,例如:

  1. 這兩個函數serializeCookiesetMultipleCookies永遠不會被調用。

  2. 如果您確實打算使用serializeCookie ,那么它寫入數據的方式非常不一致。 if有的話,真的不應該進行任何類型檢查。 它應該總是這樣做:

     value = JSON.stringify(value);

    function 可能只是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM