再次记录用了很久的一个vue接口封装方法(非原创)
import axios from "axios";
var VUE_API_URL = "../plugins/index"
const instance = axios.create({
baseURL: VUE_API_URL,
timeout: 10000
});
const defaultOpt = {login:false};
// 接收数据
const request = ["post", "put", "patch" , "get", "delete", "head"].reduce((request, method) => {
request[method] = (url, data = {}, options = {}) => {
return baseRequest(
Object.assign({ url, data, method }, defaultOpt , options)
);
};
return request;
}, {});
//处理请求
function baseRequest(options){
const headers = options.headers || {};
if(options.login == true){
headers["Authori-zation"] = getCOOKIE("token")
}
options.headers = headers;
return instance(options).then(res => {
const data = res.data || {};
//删除登录标识
delete options.login;
//请求失败
if (res.status !== 200)
return Promise.reject({ msg: "请求失败", res, data });
if(data.code === 200){
return Promise.resolve(data,res);
}else{
return Promise.reject(data,res);
}
});
}
function getCOOKIE(c_name) {
if (document.COOKIE.length>0)
{
var c_start=document.COOKIE.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
var c_end=document.COOKIE.indexOf(";",c_start)
if (c_end==-1) c_end=document.COOKIE.length
return unescape(document.COOKIE.substring(c_start,c_end))
}
}
return ""
};
export default request;
import request from "../plugins/request";
export function signIn(phone,code) {
return request.post("/user/login",{phone:phone,code:code},{login:false});
}