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);
question from:
https://stackoverflow.com/questions/65927023/401-error-when-sending-axios-get-request-with-auth-headers 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…