安装axios
npm install axios --save
封装axios
创建文件
src/util/request.js
import axios from 'axios'
// http://www.axios-js.com/zh-cn/docs/index.html
const http = axios.create({
baseURL: '',
timeout: 10000,
// headers: {'X-Custom-Header': 'foobar'}
});
// 添加请求拦截器
http.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
http.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
export default http ;
集中处理请求
src/api/index.js
import http from '../utils/request'
//GET
export const getInfo = ()=>{
return http.get( '/api/url' )
}
// GET
export const getInfoWithParams = (params)=>{
/*
注意此处传入的params需要是一个对象
即:
{
params:{}
}
外层的{}不可省略
*/
return http.get( '/api/url',params)
}
// POST
export const postWithData = (data)=>{
return http.post( '/api/url',data)
}
发送请求
// 导入
import {getInfo} from '../api'
// 发送请求并解析
getInfo().then(
({data}) => {
// 处理数据
}
);
创建代理
创建代理文件:在Vue项目的根目录中创建一个名为vue.config.js的新文件,并添加以下代码:
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8080',
changeOrigin: true
}
}
}
}
Citation:
References: