该问题的解决方法是在Axios中添加请求头,包括Authorization和Content-Type,其中Authorization需要在登录时获取token,并在请求时添加到请求头中。代码示例如下:
//登录请求
axios.post('/login', {
username: 'username',
password: 'password'
})
.then(response => {
const token = response.data.token;
//将token存储在本地 or 全局变量中
localStorage.setItem('token', token)
})
.catch(error => {
console.log(error);
})
//API请求
axios.post('/api', {
data: 'data'
}, {
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
})