简体   繁体   中英

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

In 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:

Here is my Endpoint in 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:

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. it gives me a Preflight

I am assuming you are using Express.

In order to handle JSON post data in express, you must use the express.json() middleware on your app. The middleware parses the JSON, and turns it into a native js object, binding it to request.body .

Then, you can access the contents of the JSON like this:

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.

Instead, the JWT should be stored either in client-side 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.

Is axios.post send data is 'http://localhost:5000/otp/token/verify'.

But server router 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.

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.

express documentation : 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM