无法在 axios.get 请求中传递不记名令牌

问题描述 投票:0回答:1

我正在尝试使用 axios 进行 api 调用,如果我使用 put、post 或 delete 方法,那么我可以在标头中传递不记名令牌,但在 get 方法中不能传递

const config = { headers: { Authorization: `Bearer ${token}` } };

这个获取请求不起作用

axios.get(
        "http://localhost:3001/api/message/",
        {
          chatId: "661925ba21df3cb3dc4958be",
        },
        config
      )
      .then(async (results) => {
        console.log(results);
      })
      .catch((error) => {
        console.log(error);
      });

但这个帖子请求有效

axios.post(
        "http://localhost:3001/api/message/",
        {
          chatId: "661925ba21df3cb3dc4958be",
        },
        config
      )
      .then(async (results) => {
        console.log(results);
      })
      .catch((error) => {
        console.log(error);
      });

我刚刚将 get 更改为 post 并且不记名令牌包含在标头中,get 方法有什么问题?

javascript reactjs axios
1个回答
0
投票

axios.get / axios.post 的语法不同:

axios.get('/api', {headers: {}, params: {}});

axios.post('/api', {msg: 'here is your data object'}, {headers: {}, params: {}})

顺便说一句,您可以使用拦截器来使其更容易:

axios.interceptors.request.use(config => {
   const token = localStorage.getItem('TOKEN')
   if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
   }
})
© www.soinside.com 2019 - 2024. All rights reserved.