简单示例代码:
请求网络的js逻辑,可以放到request.js文件中,放在目录utils下;
import axios from "axios";
axios.defaults.withCredentials=true;
//创建axios实例
const instance = axios.create({
// `headers` 请求头的通用配置
headers: {
// 'X-Requested-With': 'XMLHttpRequest'
},
baseURL: 'https://localhost:8080/api',//远程的api地址
timeout: 120000, // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
withCredentials: false, // `withCredentials` 表示跨域请求时是否需要使用凭证
});
// 请求拦截器
instance.interceptors.request.use(
config => {
// 设置Content-Type、token等等
if(!config.headers["Content-Type"]){
config.headers["Content-Type"]="application/json";
}
config.headers["auth"]=localStorage.getItem("token");
//config.headers["openid"]=localStorage.getItem("openid");
return config;
},
error => {
//统一错误处理...
return Promise.reject(error);
}
);
// 响应拦截器
instance.interceptors.response.use(
response => {
if (response.status === 200) {
if(response.data.ResultCode==401){//说明token过期或者鉴权失败
alert('鉴权失败,您将强制退出登录');
//清空token
localStorage.removeItem("token");
//跳转到登录页
return router.push('/login');
}
return response.data;
//return response; // 正常返回
} else {
return Promise.reject(reponse);
}
},
error => {
//错误处理...
return Promise.reject(error);
}
);
//http post请求
const post = (url,query) => {
return instance.post(url,JSON.stringify(query));
};
//http get请求
const get = (url,query) => {
return instance.get(url,query);
};
function request(config) {
return instance.request(config);
}
function jsonp(url, jsonp='callback') {
if (!window) console.error('当前为非浏览器环境,发送jsonp失败');
return new Promise((resolve, reject) => {
let _script = document.createElement('script');
_script.type = 'text/javascript';
let _callbackFunctionName = '__axios__yt__callback'+Date.now();
_script.src = (/\?[^=]+=/.test(url)) ? (url+'&'+jsonp+'='+_callbackFunctionName) : (url+'?'+jsonp+'='+_callbackFunctionName)
window[_callbackFunctionName] = (result) => {
resolve(result);
document.getElementsByTagName('head')[0].removeChild(_script); //删除临时script标签
window[_callbackFunctionName] = null; //删除临时回调
}
document.getElementsByTagName('head')[0].appendChild(_script);
})
}
export default {
instance,
request,
jsonp,
post,get
}