首页 > 解决方案 > UnhandledPromiseRejectionWarning:来自 Node JS 的未处理的承诺拒绝,React 中的预检响应

问题描述

在反应 JS 中:

这是我的代码:

....some code......

verifyTokenResults = await axios.post('http://localhost:5000/otp/token/verify', {accessToken: authToken})

上面,我通过 request.body 将一个令牌从 React 发布到下面的 Node JS 路由:

这是我在 Node JS / Express JS 中的端点:

router.post('/token/verify', async (request, response) =>{
    const tokenToVerify = request.body.accessToken;
    console.log(tokenToVerify);

    let cachedToken;
    let individualAccessToken;
    let emailWithToken;
    

    if (tokenToVerify) {
        cachedToken = await accessTokenModel.find({accessToken: tokenToVerify}).sort({_id: -1}).limit(1);
        //access the accessToken key of the returned json

        for (let record of cachedToken) {
            individualAccessToken = record["accessToken"];
            emailWithToken = record["email"];
        }

        if (individualAccessToken === tokenToVerify) {
            return response.status(200).json({message: `JWT Token Verified Successfully!`});
        } else {
            return response.status(404).json({message: `Invalid JWT Token!`});
        }
    }


  });

**这是我在使用 try...catch 包装我的方法之前在 Node JS 控制台中遇到的错误:

我收到以下错误:**

(node:2252) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'accessToken' of undefined

(node:2252) 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: 3)

当我用 try...catch 包装函数时,In React 在完成请求后不会继续前进。它给了我一个预检

标签: javascriptnode.jsreactjsexpress

解决方案


我假设您使用的是 Express。

为了快速处理 JSON 发布数据,您必须express.json()在应用程序上使用中间件。中间件解析 JSON,并将其转换为原生 js 对象,将其绑定到request.body.

然后,您可以像这样访问 JSON 的内容:

const tokenToVerify = request.body.accessToken

旁注:在服务器端存储 JWT 完全违背了 JWT 的目的,即消除存储会话数据的需要。

相反,JWT 应该存储在客户端 localStorage 中。然后,在后续请求中,客户端在请求的授权标头中设置其访问令牌。

您还可以将 JWT 设置为 httpOnly cookie,访问令牌将与后续请求一起发送。


推荐阅读