0
votes

In my react project, I have been using axios to help get data from MongoDB.

My axios get requests return a 401 error when I add my auth middleware as a param. This middleware requires the user to have a valid JWT token before any data is returned.

When making the request with Insomnia/Postman, as long as long as the user token is added to the request headers, I always get the desired data returned. However, when I try to get the data within the react application, I get a "Failed to load resource: the server responded with a status of 401 (Unauthorized)" error log, along with my custom json error response, "No Auth token, authorisation denied!"

I built a simple boolean function that returns true if the current user has a valid JWT token. Despite returning true, I am still receiving the 401 error as a response, which leads me to suspect there is a syntax or formatting error somewhere inside my react code.

Backend (with express):

router.get("/allauth", auth, async (req, res) => {
 const players = await Player.find();
  res.json(players);
}); 

Auth:

const jwt = require("jsonwebtoken");

const auth = (req, res, next) => {
 try { 
    const token = req.header("x-auth-token"); 
    
    if (!token)
        return res.status(401)
        .json({ msg: "No Auth token, authorisation denied!" });

    //match token against .env password
    const verified = jwt.verify(token, process.env.JWT_SECRET);

    if (!verified)
        return res.status(401)
        .json({ msg: "Token verification failed, authorisation denied!" });

    req.user = verified.id;
    next(); 

    } catch (err) {
        res.status(500).json({ error: err.message });
 }
};

React frontend:

export default function DisplayTeam() {

const [players, setPlayers] = useState([]);
const {userData} = useContext(UserContext);

 useEffect(() => {
    let token = localStorage.getItem("auth-token");
    const url = "http://localhost:5000/players";
    console.log(token);

    axios.get(`${url}/allauth`, {
        headers: {
            "Authorization": `x-auth-token ${token}`
        }
    })
        .then( response => setPlayers(response.data))
        .catch( error => console.log(error));
 }, []);

return (//display from DB);
1

1 Answers

2
votes

Based on your server config, you need to pass X-Auth-Token header not Authorization,

it should be:

headers: {
  "X-Auth-Token": token
}

Also, Take into consideration that headers are Case Sensitive!