1. 安装
npm i axios -S
2. 配置
utils/api.js
import axios from "axios";
axios.defaults.baseURL = 'http://localhost:8080'
/**
* 创建axios实例
* @type {AxiosInstance}
*/
const http = axios.create({
timeout: 10 * 1000,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
})
/**
* 请求头添加上token
*/
http.interceptors.request.use(config => {
// config.headers['Authorization'] = localStorage.getItem('token') // 请求头带上token
return config
}, error => {
return Promise.reject(error)
})
/**
* 相应拦截器,取出响应的数据
*/
http.interceptors.response.use(config => {
return config.data
})
export default http
3. main.js中挂载
import axios from "axios";
Vue.prototype.$http = axios