Problem wiring a nodejs express back-end with a reactjs front-end

186 Views Asked by At

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

2

There are 2 best solutions below

8
Saikat Chakrabortty On

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.

0
Riyesh On

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.