Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript Express.js unhandledPromisejectionWarning:未处理的承诺拒绝_Javascript_Node.js_Promise - Fatal编程技术网

Javascript Express.js unhandledPromisejectionWarning:未处理的承诺拒绝

Javascript Express.js unhandledPromisejectionWarning:未处理的承诺拒绝,javascript,node.js,promise,Javascript,Node.js,Promise,因此,我有以下代码: 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.pas

因此,我有以下代码:

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.
我正在努力实现的目标:

我的登录功能以前确实有效,为了设置多个cookie,需要一些拉皮条的功能。我在这里发现了一个问题,我再也找不到了,上面说有一个bug和一些注释,可能已经修复了,但是没有发现任何证据,因为代码根本不起作用。所以我不得不做这个黑客,我在我的代码中实现了它,它给了我这些错误。
set\u cookies=['loggedinid',id]
应获取第二个cookie作为键loggedinid和值变量id。id是MongoDB id名称

至少这些问题:

  • forEach
    回调中的任何位置都没有
    wait
    ,因此将该回调标记为
    async
    没有任何意义。删除那个关键词,你就不会再收到未经处理的拒绝承诺了。更改:

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

  • 以下语句引用了不存在的
    标题
    属性:

    set_cookies.push('access_token'+ 'Bearer'+token).header("Set-Cookie", set_cookies)
               .json(user);
    
    push
    的返回值是一个整数,因此不能对其调用
    .header()
    。这会引发一个异常。可能您打算在
    res
    上调用
    .header()

    set_cookies.push('access_token'+ 'Bearer'+token);
    res.header("Set-Cookie", set_cookies)
       .json(user);
    
  • 此行中有一个未定义的变量
    id

    set_cookies = ['loggedinid', id]
    
    我真的无法说出您在这里的意图,但您应该确保
    id
    已经定义并具有适当的值

  • 从未定义
    serializeCookie
    中的变量
    val
    。可能您想要

  • 还有其他与您的问题无关的问题,例如:

  • 从未调用两个函数
    serializeCookie
    setMultipleCookies

  • 如果您确实打算使用
    序列化cookie
    ,那么它在写入数据的方式上是非常不一致的。确实不应该有任何类型检查
    if
    。它应该始终做到:

    功能可以是:

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

  • forEach
    回调中的任何位置都没有
    wait
    ,因此将该回调标记为
    async
    没有任何意义。删除那个关键词,你就不会再收到未经处理的拒绝承诺了。更改:

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

  • 以下语句引用了不存在的
    标题
    属性:

    set_cookies.push('access_token'+ 'Bearer'+token).header("Set-Cookie", set_cookies)
               .json(user);
    
    push
    的返回值是一个整数,因此不能对其调用
    .header()
    。这会引发一个异常。可能您打算在
    res
    上调用
    .header()

    set_cookies.push('access_token'+ 'Bearer'+token);
    res.header("Set-Cookie", set_cookies)
       .json(user);
    
  • 此行中有一个未定义的变量
    id

    set_cookies = ['loggedinid', id]
    
    我真的无法说出您在这里的意图,但您应该确保
    id
    已经定义并具有适当的值

  • 从未定义
    serializeCookie
    中的变量
    val
    。可能您想要

  • 还有其他与您的问题无关的问题,例如:

  • 从未调用两个函数
    serializeCookie
    setMultipleCookies

  • 如果您确实打算使用
    序列化cookie
    ,那么它在写入数据的方式上是非常不一致的。确实不应该有任何类型检查
    if
    。它应该始终做到:

    功能可以是:

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

  • 假设
    sorted
    是一个数组,那么从异步回调到
    sorted.forEach
    async([firstname,password])=>{…}
    的任何错误都不会被捕获到
    catch
    块中。尝试执行
    wait Promise.all(sorted.map(async([firstname,password])=>{…}))
    ,它将每个项目映射到一个承诺,然后等待所有承诺得到解决。@Cherryblosson仍在获取
    (节点:352)未处理的Promisejection警告:未处理的承诺拒绝。此错误源于在没有catch块的异步函数中抛出,或者拒绝未使用.catch()处理的承诺。要在未处理的承诺拒绝时终止节点进程,请使用CLI标志--unhandled rejections=strict`(请参阅)。(拒绝id:2)(节点:352)[DEP0018]弃用警告:未处理的承诺拒绝已弃用。将来,承诺拒绝…`://还有
    (节点:352)未处理的PromiserEjectionWarning:ReferenceError:id未定义
    假设
    已排序
    是一个数组,则从异步回调引发的任何错误都将被排序。forEach
    异步([firstname,password])=>{code>)不会在
    catch
    块中被捕获。尝试执行
    wait Promise.all(sorted.map(async([firstname,password])=>{…}))
    ,它将每个项目映射到一个承诺,然后等待所有承诺得到解决。@Cherryblosson仍在获取
    (节点:352)未处理的Promisejection警告:未处理的承诺拒绝。此错误源于在没有catch块的异步函数中抛出,或者拒绝未使用.catch()处理的承诺。要在未处理的承诺拒绝时终止节点进程,请使用CLI标志--unhandled rejections=strict`(请参阅)。(拒绝id:2)(节点:352)[DEP0018]弃用警告:未处理的承诺拒绝已弃用。将来,承诺拒绝…`://还有
    (节点:352)未处理的PromisejectionWarning:ReferenceError:id未定义
    我一定是做错了什么。。。我听从了Cherryblosson的建议,然后又听从了你的建议,我似乎得到了同样的错误…你删除了
    async
    ?只是从
    sorted.map中删除了(([firstname,password…
    。请给我一秒钟时间进行测试。我在您的问题代码中没有看到排序的
    。map
    。这令人困惑。我在问题注释中遵循了Cherryblosson的建议,因此