在项目下新建一个service文件夹(与package.json同级),
子文件:http.js 对axios请求头、拦截器等,
reset.js:请求方法的封装,get,post等。
1. config.js
```
// import { Message, MessageBox } from "element-ui";
export const RESPONSR_CODE = {
/* 50008: '非法的token',
50012: '其他客户端登录了',
50014: 'Token 过期了' */
2: res=> {
return res.result.msg;
},
3: res=> {
return res.result.msg;
}
};
export const ERROR_MESSAGE = {
400: "服务器连接失败",
401: "服务器连接失败",
403: "服务器连接失败",
404: "请求出错(404)",
408: "服务器连接失败",
500: "服务器连接失败",
501: "服务器连接失败",
502: "服务器连接失败",
503: "服务器连接失败",
504: "网关超时(504)",
505: "服务器连接失败"
};
export function MessageTip(message,cb) {
/*
Message.closeAll();
Message({
message:message,
type: "error",
duration: 3 * 1000
});
*/
alert(message);
cb && cb();
}
export const CONFIG_FORMAT = {
encode: config=> {
leturl =config.url;
url += "?";
let keys =Object.keys(config.params);
for (let key of keys) {
url += `${key}=${encodeURIComponent(config.params[key])}&`;
}
url =url.substring(0,url.length - 1);
config.params = {};
config.url =url;
return config;
},
token: config=> {
if (window.localStorage.getItem("token")) {
let token = JSON.parse(window.localStorage.getItem("token")).token;
if (token.length > 0) {
config.headers["token"] =token;
}
return config;
} else {
MessageTip("请先登录", () => {
return Promise.reject("请先登录");
});
}
},
upload: config=> {
config.tomeout = 600000;
return config;
},
path: config=> {
config.baseURL = "";
return config;
}
};
```
2. http.js
```
//axios请求头、拦截器等
import axios from"axios";
import {
RESPONSR_CODE,
ERROR_MESSAGE,
MessageTip,
CONFIG_FORMAT
} from"./config";
// 创建axios实例
const service =axios.create({
baseURL: "/api",
timeout: 5000
});
service.defaults.headers.post["Content-Type"] = "application/json";
// request拦截器
service.interceptors.request.use(
config=> {
config.headers["x-access-gwpcm-token"] =config["token"];
if (config.type &&config.type === "encode") {
config = CONFIG_FORMAT.encode(config);
}
return config;
},
error=> {
Promise.reject(error);
}
);
// response 拦截器
service.interceptors.response.use(
response=> {
constres =response.data;
if (+res.result.code === 1) {
return res;
} else {
letmessage =RESPONSR_CODE[+res.result.code];
MessageTip(message(res), () => {
return Promise.reject("error");
});
}
},
error=> {
letmessage = "";
if (error.response) {
letmsg =ERROR_MESSAGE[+error.response.status];
message =msg || "服务器连接失败";
} else if (error.message.includes("timeout")) {
message = "服务器访问超时,请重试!";
}
MessageTip(message, () => {
return Promise.reject(error);
});
}
);
export default service;
```
3. request.js
```
import interfaces from"./interface";
const Interface =Object.assign({},interfaces);
export default Interface;
```
4. reset.js
```
//请求方法的封装,get,post等
import http from'./http.js'
export default {
post(url,data,config) {
return http.post(url,data,config)
},
get(url,params,config) {
const getConfig = {}
if (params) {
Object.assign(getConfig, {
params
})
}
if (config)Object.assign(getConfig,config)
return http.get(url,getConfig)
},
put(url,data,config) {
return http.put(url,data,config)
},
delete(url,params,config) {
const delConfig = {}
if (params) {
Object.assign(delConfig, {
params
})
}
if (config)Object.assign(delConfig,config)
return http.delete(url,delConfig)
},
patch(url,params,config) {
return http.patch(url,params,config)
}
}
```
5. 创建interface文件夹
6. 在interface文件夹下创建index.js
```
/\*\*
\* The file enables `@/interface/index.js` to import all axios modules
\* in a one-shot manner. There should not be any reason to edit this file.
\*/
const files =require.context(".", false, /\.js$/);
let modules = {};
files.keys().forEach(key=> {
if (key === "./index.js") return;
modules = {...modules, ...files(key) };
});
export default modules;
```
7. 在interface文件夹下创建接口文件
示例:
login.js文件
```
//api封装使用
import request from"../reset"; // axios的封装 后续添加axios二次封装
// 获取专题列表数据
export function Login(query = {},config = {}) {
return request.post(`/login`, query, config);
}
```
8. 在main.js中引入接口文件
```
// 引入request文件
import Request form "@/.../request";
Vue.prototype.$request = Request;
```
9. 在项目中使用
```
this.$request.Login({loginName:'aaa',password:'bbb'})
.then(res => {console.log(res)})
.catch(err => {console.log(err)})
```