Home > Net >  Send jwt to API in request header from Reactjs frontend
Send jwt to API in request header from Reactjs frontend

Time:09-16

I have a quick question. I am using Axios to send requests to the nodejs API, when I set the token in the request header the API returns "jwt must be provided". The API expects the token with a custom name attached to it - here's how far I've gotten.

Snippet of API code that sends the token on login

const token = jwt.sign(
              {
                userID: result[0].userID,
                firstName: result[0].firstName,
                lastName: result[0].lastName,
                email: result[0].email,
                role: result[0].role,
                // exp: Math.floor(Date.now() / 1000)   60 * 60,
              },
              "HeyImaPrivateKeyyy"
            );
            res.json({ token });
            console.log("Login Attempt", res.statusMessage, req.body);
          } else {
            res.status(400).send({ message: "Invalid credentials!" });
            console.log("Login Attempt", res.statusMessage, req.body);
          }
        

-- React code from here --

Response from API on successful login

{
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySUQiOjEsImZpcnN0TmFtZSI6IkNhbWVyb24iLCJsYXN0TmFtZSI6IkVyYXNtdXMiLCJlbWFpbCI6ImNhbWVyb25AY2xpZnRjb2xsZWdlLmNvbSIsInJvbGUiOiJzdXBlckFkbWluIiwiaWF0IjoxNjYzMzEzNTM2fQ.9R6vXn-5Vb5fj48eUJGPNUGnXMw9TXOjJCox7U36WMI"
}

Saving the token on successful login (React)

const login = async ({ email, password }) => {
    const res = await api.post(
      "/auth",
      {
        email: email, //varEmail is a variable which holds the email
        password: password,
      },
      {
        headers: {
          "Content-type": "application/json",
          Authorization: false,
        },
      }
    );
    const { from } = state || {};

    let token = jwt(res.data.token);

    setToken("x-auth-token", token); // your token
    localStorage.setItem("x-auth-token", res.data.token);
    localStorage.setItem("userLogged", true);
    localStorage.setItem("name", token.firstName);
    localStorage.setItem("role", token.role);
    navigate("/auth/dashboard" || from.pathname, { replace: true });
  };

Here is the React component that is trying to call the API

const [count, setCount] = useState(null);

  const token = localStorage.getItem("x-auth-token");

  const studentCount = useEffect(() => {
    const config = {
      headers: { "x-auth-token": token },
      "Content-type": "application/json",
    };

    api.get("/students/", {}, config).then((response) => {
      setCount(response.data);
    });
  }, [token]);

  if (!count) return null;

This is what the API is expecting on request

export const teacher = (req, res, next) => {
  const token = req.header("x-auth-token");
  if (!auth && !token)
    return res.status(401).send({ message: "Access denied." });

  const decoded = jwt.verify(token, "DemoPrivateKey");
  if (auth && ["superAdmin", "admin", "teacher"].includes(decoded.role)) {
    next();
  } else {
    res.status(400).send({ message: "Access denied!" });
  }
};

Ideally, I would like to send the token as a header on successful login, but it saves as undefined on the client (have no idea how to fix that).

CodePudding user response:

If you're using Axios then, as per the doc, get method should have config parameter in second position not third one. So maybe, simply updating api.get("/students/", {}, config) into api.get("/students/", config) should solve your issue.

  • Related