简体   繁体   English

UnhandledPromiseRejectionWarning:来自 Node JS 的未处理的承诺拒绝,React 中的预检响应

[英]UnhandledPromiseRejectionWarning: Unhandled promise rejection from Node JS, Preflight response in React

In React JS:在 React JS 中:

Here is my code:这是我的代码:

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

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

Above, I am posting a token from React to the Node JS route below through request.body:上面,我通过 request.body 将一个令牌从 React 发布到下面的 Node JS 路由:

Here is my Endpoint in Node JS / Express 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!`});
        }
    }


  });

**Here is the error that I was getting in the Node JS console, before wrapping my method with a try...catch: **这是我在 Node JS 控制台中遇到的错误,在使用 try...catch 包装我的方法之前:

I am getting the following error:**我收到以下错误:**

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

When I wrapped the function with try...catch, In React does not move forward after it finishes with the request.当我用 try...catch 包装函数时,React 在完成请求后不会向前移动。 it gives me a Preflight它给了我一个预检

I am assuming you are using Express.我假设您正在使用 Express。

In order to handle JSON post data in express, you must use the express.json() middleware on your app.为了在 express 中处理 JSON post 数据,你必须在你的应用中使用express.json()中间件。 The middleware parses the JSON, and turns it into a native js object, binding it to request.body .中间件解析 JSON,并将其转换为原生 js 对象,将其绑定到request.body

Then, you can access the contents of the JSON like this:然后,您可以像这样访问 JSON 的内容:

const tokenToVerify = request.body.accessToken

Side note : storing JWT server-side comepletely defeats the purpose of JWT, which is to eliminate the need for storing session data.旁注:存储 JWT 服务器端完全违背了 JWT 的目的,即消除存储会话数据的需要。

Instead, the JWT should be stored either in client-side localStorage.相反,JWT 应该存储在客户端 localStorage 中。 Then, in subsequent requests the client sets its access token in the authorization header of the request.然后,在后续请求中,客户端在请求的授权标头中设置其访问令牌。

You could also set the JWT as a httpOnly cookie, and the access token will be sent along with subsequent requests.您还可以将 JWT 设置为 httpOnly cookie,访问令牌将与后续请求一起发送。

Is axios.post send data is 'http://localhost:5000/otp/token/verify'. axios.post 发送数据是'http://localhost:5000/otp/token/verify'。

But server router url router.post('/token/verify');但是服务器路由器 url router.post('/token/verify');

The URL from which the client sends data and the URL where the server receives data are different from the path.客户端发送数据的URL和服务器接收数据的URL与路径不同。

That is, the server cannot receive data from the client.也就是说,服务器无法从客户端接收数据。

fix,使固定,

Some of the things I explained were not answered.我解释的一些事情没有得到回答。 You need to request the data with req.body, not req.data as in the answer above.您需要使用 req.body 请求数据,而不是上面的答案中的 req.data。

express documentation : https://expressjs.com/ko/api.html快速文档: https : //expressjs.com/ko/api.html

The problem, as the error message says, seems to be related to the key you are using to access request data.正如错误消息所说,问题似乎与您用来访问请求数据的密钥有关。 Do also check if you are using the right middleware.还要检查您是否使用了正确的中间件。

According to this documentation根据这个文件

https://expressjs.com/en/4x/api.html#req.body https://expressjs.com/en/4x/api.html#req.body

To access request body data you should refer to the following key要访问请求正文数据,您应该参考以下键

request.body

Apart for this issue, ensure to take in consideration the suggestions you are receiving in the comments section of your question.除了这个问题,请确保考虑您在问题的评论部分收到的建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Node.js:未处理的承诺拒绝 - UnhandledPromiseRejectionWarning - Node.js: Unhandled promise rejection - UnhandledPromiseRejectionWarning UnhandledPromiseRejectionWarning:Node.JS中未处理的承诺拒绝(拒绝ID:1) - UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1) in Node.JS (节点:52585)UnhandledPromiseRejectionWarning:未处理的 promise 拒绝 - (node:52585) UnhandledPromiseRejectionWarning: Unhandled promise rejection (节点:2256)UnhandledPromiseRejectionWarning:未处理的 promise 拒绝 - (node:2256) UnhandledPromiseRejectionWarning: Unhandled promise rejection (节点:4677)UnhandledPromiseRejectionWarning:未处理的承诺拒绝 - (node:4677) UnhandledPromiseRejectionWarning: Unhandled promise rejection Express.js UnhandledPromiseRejectionWarning: 未处理的 promise 拒绝 - Express.js UnhandledPromiseRejectionWarning: Unhandled promise rejection 如何解决UnhandledPromiseRejectionWarning:未处理的promise promise:TypeError:仅支持绝对URL? Node.js的 - How to solve UnhandledPromiseRejectionWarning: Unhandled promise rejection: TypeError: Only absolute URLs are supported? Node.js UnhandledPromiseRejectionWarning:未处理的承诺拒绝错误,我正在使用 Node JS 和 mongo Db - UnhandledPromiseRejectionWarning: Unhandled promise rejection error I am getting I am using Node JS and mongo Db UnhandledPromiseRejectionWarning:未处理的承诺拒绝 - API - UnhandledPromiseRejectionWarning: Unhandled promise rejection - API UnhandledPromiseRejectionWarning:未处理的 API 承诺拒绝 - UnhandledPromiseRejectionWarning: Unhandled promise rejection for API
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM