Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

javascript - 401 Error when sending axios get request with Auth Headers

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...