JWT token not authenticating when deployed to Heroku

Viewed 27

I am having some problems with authenticating my JWT token after i have generated it. so once a verified user logs in a token will be generated and the user will be navigated to the dashboard where the token will be verified. if the verification is succesfull, the dashboard will be displayed else it will redirect back to the login page. I have been able to generate the token but the authentication is the problem. it works fine running it locally but it dosent work when served on heroku. it redirects back to the login immediatley i log in.

const getCurrentUser = () => {
    let endpoint = [*****************************************];
    let token = localStorage.token;
    axios
      .get(endpoint, {
        headers: {
          Authorization: `Bearer ${token}`,
          "content-Type": "application/json",
          Accept: "application/json",
        },
      })

      .then((res) => {
        console.log(res);
        if (res.data.status) {
          setActiveUser(res.data.result);
          dispatch(currentUser(res.data.result));
          setLoading(true);
        } else {
          // navigate("/");
        }
      });
  };

this is the controller for the route to the API

const getCurrentUserInfo = (req, res) => {
  console.log(req.headers);
  let token = req.headers.authorization.split(" ")[1];

  jwt.verify(token, JWT_SECRET, (err, result) => {
    console.log(err, result);
    if (err) {
      res.send({ status: false });
    } else {
      userModel.findOne({ email: result.email }, (err, result) => {
        if (err) {
          res.send({ status: false });
        } else {
          res.send({ result, status: true });
        }
      });
    }
  });
};

I tried using postmate to test the API but its returning a react HTML page. Also the console.log on the server side does not get triggered when i make an GET request to the API. This is what my server looks like. i have tried to reorder the codes but it did not work

const express = require("express");
const App = express();
const mongoose = require("mongoose");
const cors = require("cors");
const port = process.env.PORT || 3000;
const URI = process.env.URI;
const userRouter = require("./Routes/user.route");

require("dotenv").config();
App.use(express.static("./build"));
App.get("/*", (req, res) => {
  res.sendFile(__dirname + "/build/index.html");
});
App.use(express.urlencoded({ extended: true, limit: "50mb" }));
App.use(express.json({ limit: "50mb" }));
App.use(cors());
App.use("/user", userRouter);

App.listen(port, () => {
  console.log("Server is running on port " + port);
});

mongoose.connect(URI, (err) => {
  if (err) {
    console.log("Mongoose did not connect");
  } else {
    console.log("mongoose connected successfully");
  }
});
0 Answers
Related