登录当前用户存储token
1.假设后端API的地址是http://localhost:3000/api,可以创建一个js文件(api.js)
import axios from 'axios';
const instance = axios.create({
baseURL: '/api',
timeout: 5000
});
instance.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
}, error => {
return Promise.reject(error);
});
export default instance;
2.在需要的组件中传入这个文件
import api from '@/api.js'
export default {
data() {
return {
userList: []
}
},
mounted() {
api.get('/user/list')
.then(response => {
this.userList = response.data;
})
.catch(error => {
console.log(error);
});
}
}
3.登录成功后,将token保存到localStorage中
methods: {
login() {
axios.post('/api/login', { username: this.username, password: this.password })
.then(response => {
localStorage.setItem('token', response.data.token);
this.$router.push('/home');
})
.catch(error => {
alert(error.response.data.error);
});
}
}
这样就配置好了axios和js,可以使用api.get()、api.post()等方法进行API请求,并自动添加token信息到请求头中。