简体   繁体   中英

Can`t find JSON Web Token from headers

I have set up JWT to be set in localstorage whenever someone logins or registers. And it works, I can see the token in localstorage. But when I set the token in the headers with axios, node.js in the backend can`t find the token. Like it does not exists. I have checked it in the front end, I get logs of the token in the headers. And also when I request from postman it works. Here is the code.

setAuthToken function = {
  const instance = axios.create({
    baseURL: "https://localhost:5000",
  });

  if (token) {
    instance.defaults.headers.common["x-auth-token"] = `${token}`;
    console.log(instance.defaults.headers.common["x-auth-token"]);
  } else {
    delete instance.defaults.headers.common["x-auth-token"];
  }
}

const loadUser = async () => {
    if (localStorage.token) setAuthToken(localStorage.token);
    console.log(localStorage.token);

    try {
      const res = await axios.get("/api/users");
      console.log(res);

      dispatch({ type: USER_LOADED, payload: res.data });
    } catch (err) {
      console.log(err.response.data.msg);
      dispatch({ type: AUTH_ERROR });
    }

The request comes to the await axios statement and goes to catch so error is in the request.

Here is the backend code

// Get current user

router.get("/", auth, async (req, res) => {
  try {
    const user = await User.findById(req.user.id);
    res.status(200).json({ user });
  } catch (err) {
    console.log(err);
    res.status(500).json({ msg: `Server Error` });
  }
});

auth middleware function here = {
const token = req.headers["x-auth-token"];
  console.log(token, "token in auth.js");
  console.log(req.headers, "req.header");

 

     if (!token) {
        return res.status(401).json({ msg: `Access denied.` });
      }

 

     try {
        const decoded = jwt.verify(token, config.get("jwtSecret"));
    
        req.user = decoded.user;
        next();
      } catch (err) {
        res.status(401).json({ msg: `Token is not valid` });
      }
    }

I`m new to backend develoment and axios. Can someone help me please. Thank you Here are the console.logs

Logs

Logs

Little update, it looks like there is a problem with proxy, I am using my own backend api, and also movie data base api. So maybe thats why I cant set headers? Here are new logs:

config: Object { url: "/api/users", method: "get", timeout: 0, … }
​
data: "Proxy error: Could not proxy request /api/users from localhost:3000 to http://localhost:5000/ (ECONNREFUSED)."
​
headers: Object { connection: "keep-alive", date: "Wed, 05 May 2021 13:18:05 GMT", "keep-alive": "timeout=5", … }
​
request: XMLHttpRequest { readyState: 4, timeout: 0, withCredentials: false, … }
​
status: 500
​
statusText: "Internal Server Error

I think the issue is because you are setting you are setting up your instance wrongly set up your instance in a new file config.js -

 import Axios from 'axios';
const baseURL = "http://localhost:5000";
const axiosInstance = Axios.create({
  baseURL: baseURL,
});
axiosInstance.interceptors.request.use(
  function (config) {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    return config;
  },
  function (error) {
    return Promise.reject(error);
  }
);
export default axiosInstance;

now when making any api request instead of using axios use axiosInstance eg-

axiosInstance.get('/something').then(res => console.log(res)).catch(err => console.log(err))

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