NodeJS UnhandledPromiseRejectionWarning with promises closed

アダム・モール:

ランダムユーザーが複数のアカウントを作成するのを防ぐためにトークンを使用する登録システムを実装しているときに問題が発生しました。

コードは最後まで実行され、応答は期待どおりに機能しますが、後で警告が表示されます:UnhandledPromiseRejectionWarning:エラー[ERR_HTTP_HEADERS_SENT]:ヘッダーがクライアントに送信された後でヘッダーを設定できません

問題は44行目で発生すると言っています。これは、mongooseのsaveメソッドのcatchステートメントです。

newRegistrationToken.save()
            .then(newRegistrationToken => res.status(200).json(newRegistrationToken))
            .catch(err => res.status(500).json(err));

私は解決策を探していましたが、常に、catchステートメントが欠落していて、この警告が表示されるという答えがありました。ただし、私のコードでは、不足しているcatchステートメントは表示されないため、ここで少し迷っています。

ルート全体は次のとおりです。

router.post('/create', (req, res) => {
    const { errors, isValid } = validateRegistrationToken(req.body);
    if(!isValid) return res.status(400).json(errors);

    // Searching for an active token associated with the e-mail address given
    console.log("search for active token");
    ModelRegistrationToken.findOne({
        email: req.body.email,
        expiresAt: { $gte: Date.now() }
    }).then(user => {
        // if user found
        if(user){
            // check if the user is already registered
            console.log("search for registered user");
            ModelUser.findOne({email: user.email}).then((registered) => {
                if(registered)
                    return res.status(400).json({email: 'There\'s a user already registered with the e-mail address given'});
                return res.status(400).json({email: 'The address given already has an active registration token'});
            }).catch(err => console.log(err));
        }
        
        // Otherwise create a new token
        const newRegistrationToken = new ModelRegistrationToken({
            email: req.body.email,
            expiresAt: new Date(Date.now() + Number.parseInt(config.REG_TOKEN_EXPIRATION_PERIOD) * 24 * 60 * 60 * 1000)
        });
        console.log("save token");
        newRegistrationToken.save()
            .then(newRegistrationToken => res.status(200).json(newRegistrationToken))
            .catch(err => res.status(500).json(err));
        
    }).catch(err => res.status(500).json(err));
});

私にはこれを理解できないようですので、これについてあなたの助けをお願いします。

特定のパフォーマンス:

あなたが持っている:

if (user) {
  // do stuff and call res.json
}
// do other stuff and call res.json

user存在する場合res.json2回呼び出されます。if (user)ブロックの下部に戻ってみてください

if (user) {
  // check if the user is already registered
  console.log("search for registered user");
  ModelUser.findOne({
    // ...
  }).catch(err => console.log(err));
  return; // <---------------------------------
}

// Otherwise create a new token
const newRegistrationToken = new ModelRegistrationToken({
  email: req.body.email,
  expiresAt: new Date(Date.now() + Number.parseInt(config.REG_TOKEN_EXPIRATION_PERIOD) * 24 * 60 * 60 * 1000)
});
// ...

内部でfindOneエラーが発生した場合はステータス500を送信することをお勧めします。そうしないと、応答がハングします。

}).catch(err => console.log(err));

のようなものに

}).catch(err => res.status(500).json(err));

他の場所でやっているように。

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

NodeJS UnhandledPromiseRejectionWarning

分類Dev

JS Promises - Why am I seeing the UnhandledPromiseRejectionWarning and DeprecationWarning?

分類Dev

UnhandledPromiseRejectionWarning:

分類Dev

NodeJS-UnhandledPromiseRejectionWarningを処理する方法は?

分類Dev

NodeJS: Trouble scraping two URLs with promises

分類Dev

nodejsでのPromisesとasync / await

分類Dev

NodeJs Command Prompt Windows closed immediately

分類Dev

JS Promises-UnhandledPromiseRejectionWarningとDeprecationWarningが表示されるのはなぜですか?

分類Dev

In nodejs ,how to use async/await instead of resolve promises through ''then" in transactions?

分類Dev

NodejsがNeo4jに投稿UnhandledPromiseRejectionWarning&DeprecationWarningエラー

分類Dev

NodeJSとMySQL:UnhandledPromiseRejectionWarningにつながるSQL構文のエラー

分類Dev

UnhandledPromiseRejectionWarning:MongooseServerSelectionError

分類Dev

UnhandledPromiseRejectionWarning:AccessDeniedException

分類Dev

NodeJSのAPIGmail:(node:14592)UnhandledPromiseRejectionWarning:エラー:委任が拒否されました

分類Dev

UnhandledPromiseRejectionWarning:エラー:docker-swarmで実行されているnodejsのgetaddrinfo ENOTFOUND

分類Dev

NodeJSでPromisesを使用して文字列を作成します

分類Dev

nodejsのPromises操作でのトランザクション管理

分類Dev

NodeJSはPromisesをPromise.allに変換します

分類Dev

NodeJS Promisesがres.send(data)でハングする

分類Dev

Promisesでasync / awaitを使用しているときに、netlify-lambdaがUnhandledPromiseRejectionWarningをログに記録するのはなぜですか?

分類Dev

ノードUnhandledPromiseRejectionWarning

分類Dev

UnhandledPromiseRejectionWarning on async await promise

分類Dev

単純なUnhandledPromiseRejectionWarning

分類Dev

clearTimeout後のUnhandledPromiseRejectionWarning

分類Dev

Catch in Promises

分類Dev

NodeJS + Mongoose-ヘルプが必要Promisesを使用してコードをリファクタリングする

分類Dev

ビュー、nodeJSでpromises.allから結果をレンダリングします

分類Dev

操り人形師-UnhandledPromiseRejectionWarning

分類Dev

Error: UnhandledPromiseRejectionWarning: Unhandled promise rejection

Related 関連記事

  1. 1

    NodeJS UnhandledPromiseRejectionWarning

  2. 2

    JS Promises - Why am I seeing the UnhandledPromiseRejectionWarning and DeprecationWarning?

  3. 3

    UnhandledPromiseRejectionWarning:

  4. 4

    NodeJS-UnhandledPromiseRejectionWarningを処理する方法は?

  5. 5

    NodeJS: Trouble scraping two URLs with promises

  6. 6

    nodejsでのPromisesとasync / await

  7. 7

    NodeJs Command Prompt Windows closed immediately

  8. 8

    JS Promises-UnhandledPromiseRejectionWarningとDeprecationWarningが表示されるのはなぜですか?

  9. 9

    In nodejs ,how to use async/await instead of resolve promises through ''then" in transactions?

  10. 10

    NodejsがNeo4jに投稿UnhandledPromiseRejectionWarning&DeprecationWarningエラー

  11. 11

    NodeJSとMySQL:UnhandledPromiseRejectionWarningにつながるSQL構文のエラー

  12. 12

    UnhandledPromiseRejectionWarning:MongooseServerSelectionError

  13. 13

    UnhandledPromiseRejectionWarning:AccessDeniedException

  14. 14

    NodeJSのAPIGmail:(node:14592)UnhandledPromiseRejectionWarning:エラー:委任が拒否されました

  15. 15

    UnhandledPromiseRejectionWarning:エラー:docker-swarmで実行されているnodejsのgetaddrinfo ENOTFOUND

  16. 16

    NodeJSでPromisesを使用して文字列を作成します

  17. 17

    nodejsのPromises操作でのトランザクション管理

  18. 18

    NodeJSはPromisesをPromise.allに変換します

  19. 19

    NodeJS Promisesがres.send(data)でハングする

  20. 20

    Promisesでasync / awaitを使用しているときに、netlify-lambdaがUnhandledPromiseRejectionWarningをログに記録するのはなぜですか?

  21. 21

    ノードUnhandledPromiseRejectionWarning

  22. 22

    UnhandledPromiseRejectionWarning on async await promise

  23. 23

    単純なUnhandledPromiseRejectionWarning

  24. 24

    clearTimeout後のUnhandledPromiseRejectionWarning

  25. 25

    Catch in Promises

  26. 26

    NodeJS + Mongoose-ヘルプが必要Promisesを使用してコードをリファクタリングする

  27. 27

    ビュー、nodeJSでpromises.allから結果をレンダリングします

  28. 28

    操り人形師-UnhandledPromiseRejectionWarning

  29. 29

    Error: UnhandledPromiseRejectionWarning: Unhandled promise rejection

ホットタグ

アーカイブ