Get request works with postman but with browser

Viewed 415

Get request sent from POSTMAN works but when sent from browser fails. At the backend req.body is undefined even after using bodyparser middleware. The same requet when sent from the POSTMAN works.

This is the axios call from the frontend.

await axios.get(`${API_URL}/api/authenticate`, {
            accesstoken: localStorage.getItem("accesstoken")
        },
            {
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'Access-Control-Allow-Origin': '*',
                    'Accept-Encoding': 'gzip, deflate, sdch'
                }
            })
            .then((res) => console.log(res))
            .catch((err) => {
                localStorage.removeItem("accesstoken");
                console.log(err)
            });

This is the backend auth handler

const isAuthenticated = (req,res,next)=>{
    const accesstoken = req.body.accesstoken;
    console.log(req.body);
    if(!accesstoken)
   {
    
    res.json({msg:"No token provided"});
   }
   else
   {
    jwt.verify(accesstoken,process.env.ACCESS_TOKEN_SECRETE,(err,decoded)=>{
        if(err)
        {
            
            res.json({msg:"Invalid token"});
        }
        else
         next();
        
    });
   }

}

These are the cors options

app.use(cors({
  origin:["http://localhost:3000","http://192.168.0.86:3000"],
  optionsSuccessStatus:200,
  credentials:true,
  allowHeaders:["Content-Type"]
}));
2 Answers

The method signature you are using for axios.get applies to axios.post where the second parameter is the request body. This doesn't hold true for axios.get. You can pass query paramters as second argument of axios.get. Postman is allowing you to make GET requests with body and the server is okay with that but it isn't advised to do so. For your use case of authentication, use POST.

I guess, you meant to do axios.post:

await axios.post(`${API_URL}/api/authenticate`, {
  accesstoken: localStorage.getItem("accesstoken")
},
  {
      headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Access-Control-Allow-Origin': '*',
          'Accept-Encoding': 'gzip, deflate, sdch'
      }
  })
  .then((res) => console.log(res))
  .catch((err) => {
      localStorage.removeItem("accesstoken");
      console.log(err)
  });
Related