[TOC] > [参考](https://www.jianshu.com/p/fed90cc60246) ### src/plugins/axios.js 设置 ``` "use strict"; import Vue from "vue"; import Axios from "axios"; import VueAxios from "vue-axios"; import { message } from "ant-design-vue"; import Qs from "qs"; //统一处理返回 Axios.interceptors.response.use( response => { //处理 非200 if (response.status !== 200) { message.error(response.statusText); } //处理失败 if (response.data.code===0){ message.error(response.data.msg) } // 对响应数据做某事 return response.data; }, error => { // 返回错误时做某事 message.error(error); } ); let config = { // config里面有这个transformRquest, 这个选项会在发送参数前进行处理。 这时候我们通过Qs.stringify转换为表单查询参数 transformRequest: [ function(data) { data = Qs.stringify(data); return data; } ], // 设置Content - Type headers: { "Content-Type": "application/x-www-form-urlencoded" }, timeout: 60000, baseURL: process.env.BASE_URL }; const axios_instance = Axios.create(config); Vue.use(VueAxios, axios_instance); ``` ### 并在main.js 中引入 `import "./plugins/axios";` ### vue.config.js 设置代理 ``` devServer: { open: false, //打开浏览器窗口 // proxy: 'http://192.168.0.59:8003/' proxy: { //配置跨域 '/api': { target: "http://192.168.0.59:8003/api", ws:true, changOrigin:true, pathRewrite:{ '^/api':'' } } } }, ``` ### 管理 api `src/api/api.js` ``` import axios from "axios"; //获取所有新闻 export const newslist=(current,page)=>{ return axios.get("/api/news/lists", { params:{page:page }}); }; ``` 调用 ``` import {newslist} from '@/api/api.js' newslist(this.current,this.defaultPageSize).then(res=>{ console.log(res); }).catch(err=>{ this.$message.error(err); }) ```