0

I am trying to put together a reactjs Dashboard and wire it up with a Nodejs back-end. I am currently trying to validate a jwt token. when I do it using a Postman app, its working fine. but when I try it using my reactjs form, its not happening. please help me find the problem in my code. I am not an experienced developer. I am kind of a newbie to both nodejs and reactjs. Any help will be highly appreciated. I will try to post all the relevant code and some snapshots below.

//reactjs code calling this function on a button submit
 //verify user

  onVerify = event => {
    let databody = localStorage.getItem("jwtToken");
    event.preventDefault();
    console.log(databody);
    fetch("http://localhost:8000/api/auth/me", {
      method: "get",
      headers: {
        "x-access-token": databody
      }
    })
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error("Something went wrong with your fetch");
        }
      })
      .then(json => {
        console.log(json.token);
      });
  };

Nodejs express backend code

//app.js
var express = require("express");

var db = require("./db");
var Cors = require("cors");

var app = express();

app.use(Cors());

var UserController = require("./user/UserController");
app.use("/users", UserController);

var AuthController = require("./auth/AuthController");
app.use("/api/auth", AuthController);

var WorkInvenController = require("./auth/WorkInvenController");
app.use("/api/workinven", WorkInvenController);

module.exports = app;

//AuthController.js


router.get("/me", function(req, res) {
  console.log(req.headers);
  var token = req.headers["x-access-token"];
  if (!token)
    return res.status(401).send({ auth: false, message: "No token provided." });

  jwt.verify(token, process.env.secret, function(err, decoded) {
    if (err)
      return res
        .status(500)
        .send({ auth: false, message: "Failed to authenticate token." });

    User.findById(decoded.id, { password: 0 }, function(err, user) {
      if (err)
        return res.status(500).send("There was a problem finding the user.");
      if (!user) return res.status(404).send("No user found.");

      res.status(200).send(user);
    });
  });
});

terminal output from the backend when posted using Postman

enter image description here

terminal output from the backend when posted using reactjs from

enter image description here

browser error attached below enter image description here

Riyesh
  • 63
  • 10
  • what is the issue you are facing exactly? both the terminal out puts are same, and its just the request details. how can you say its not working and what it should do when working? – Saikat Chakrabortty Apr 27 '19 at 02:03
  • sorry about that .. I have modified the post to add the browser error. – Riyesh Apr 27 '19 at 02:14
  • this means, your api is giving error with status code 500, can you see in the network tab ? api call response? – Saikat Chakrabortty Apr 27 '19 at 02:23
  • I did try the same with a postman and it works fine... so I guess the fetch call that I make from the reactjs end is wrong ... or Is there a problem with my headers? – Riyesh Apr 27 '19 at 03:57
  • Can you also add here the fetch request details from the Browser's Network tab? – Shobhit Chittora Apr 27 '19 at 04:49

2 Answers2

0

as i can see its a "rejection error"

you can just add .catch() and handle the error that is being thrown.

onVerify = event => {
    let databody = localStorage.getItem("jwtToken");
    event.preventDefault();
    console.log(databody);
    fetch("http://localhost:8000/api/auth/me", {
      method: "get",
      headers: {
        "x-access-token": databody
      }
    })
      .then(res => {
        if (res.ok) {
          return res.json();
        } else {
          throw new Error("Something went wrong with your fetch");
        }
      })
      .then(json => {
        console.log(json.token);
      }).catch(error=>{
     //handle the error in here may be
        console.log(error)
     });
  };

sometime we wrote some sort of wrapper as well to handle errors:

fetch(<url>, {
      <headers>,
     <options>
    })
      .then(this._checkStatus)
      .then(response => response.json());

 _checkStatus(response) {
    if (response.status >= 200 && response.status < 300) {
      // Success status lies between 200 to 300
      return response;
    }  else {
//here handle the error may be.
      var error = new Error(response.statusText);
      console.log(error);
    }
  }

so in your case, when the error coming its not handled , as there no .catch found, its throwing unhandled rejection error. you can look at the above methods and follow any of them , also let me know if you are still facing issue with this.

Saikat Chakrabortty
  • 2,520
  • 4
  • 22
  • 39
  • any idea what is causing this error in the first place? why am I not getting this error when I make a call using Postman? – Riyesh Apr 27 '19 at 10:56
  • in you frontend you are facing the error, when trying to fetch. and you didnt handle those error [even status code 500 gives error], so its coming up. above i showed how to handle. and in postman, you are actually hitting the api directly, so its showing what it gates as its, – Saikat Chakrabortty Apr 27 '19 at 11:03
  • I tried to catch the error using your code .. but its not working for me. – Riyesh Apr 29 '19 at 08:04
  • what is the issue you are facing? – Saikat Chakrabortty Apr 29 '19 at 08:31
  • if my call is correct I should be getting the user details back .. which I am not getting – Riyesh Apr 29 '19 at 09:32
  • yaa I am getting the user back when validating my token .. kinda strange right? – Riyesh Apr 29 '19 at 19:40
  • @rpserverbox right, may be in postman, can you check what is the response status code its responding with? like 200 or something? – Saikat Chakrabortty Apr 29 '19 at 20:39
  • I tried to get the error from server directly and its ``` " name: 'TokenExpiredError', message: 'jwt expired', expiredAt: 2019-04-29T20:48:51.000Z } ```. but then I used the same token to verify thorugh Postman and its working fine. – Riyesh Apr 29 '19 at 20:52
0

sorry that I didn't post the whole code up here, or else I am sure you guys would have figured it long time back. long story short.. the problem was with my token, I accidentally set the expiresIn to 60 thinking that it was 60 minutes instead of 60 * 60. so the token was expiring every next minute.

Now after setting the token expiry to "24h" everything seems working good.. thanks a lot for you help guys.

Riyesh
  • 63
  • 10