我正在尝试使用 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 方法有什么问题?
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}`
}
})