获取请求适用于邮递员但适用于浏览器

时间:2021-02-22 09:00:46

标签: node.js reactjs rest axios cors

从 POSTMAN 发送的获取请求有效,但从浏览器发送时失败。 即使在使用 bodyparser 中间件之后,后端 req.body 也是未定义的。 从 POSTMAN 发送的相同请求有效。

这是来自前端的 axios 调用。

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)
            });

这是后端身份验证处理程序

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();
        
    });
   }

}

这些是 cors 选项

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

2 个答案:

答案 0 :(得分:1)

您用于 axios.get 的方法签名适用于 axios.post,其中第二个参数是请求正文。这不适用于 axios.get。您可以将查询参数作为 axios.get 的第二个参数传递。 Postman 允许您使用 body 发出 GET 请求,服务器可以接受,但不建议这样做。对于您的身份验证用例,请使用 POST

答案 1 :(得分:0)

我猜,你的意思是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)
  });