http.js
import { qs } from 'qs';
import { message} from 'antd';
import { history } from 'umi';
const fetch = require('dva').fetch;
const CheckStatus = res=>{
if(res.status === 200) {
return res;
}
message.error(`网络错误 ${res.status}`);
const error = res.statusText;
throw new Error(error);
}
const judgeOkStatus = async(res)=>{
const cloneRes = await res.clone().json();
if(cloneRes.code !== 0) {
message.error(`${cloneRes.msg}[${cloneRes.msg}]`);
//跳转到登录页面
history.replace('/users/login');
// 清除token
sessionStorage.clear();
}
return res;
}
const handlerError = err=>{
if(err instanceof TypeError) {
message.error(`网络请求失败[${err}]`);
}
return {
code: -1,
data: false,
msg: `网络请求失败[${err}]`
}
}
class Http {
static async staticFetch(url="", options={}) {
url = '/react_oa_api' + url;
const defaultOptions = {
mode: 'cors', // 支持跨域,以CORS模式发送请求
headers: {
Authorization: sessionStorage.getItem('token') || null,
},
}
if(options.method==='POST' || options.method==='PUT') {
defaultOptions.headers['Content-Type'] = 'application/json';
}
const newOptions = {...defaultOptions, ...options};
return fetch(url, newOptions)
.then(CheckStatus)
.then(judgeOkStatus)
.then(res=>{
//获取token
const token = res.headers.get('Authorization');
if(token) {
sessionStorage.setItem('token', token);
}
return res.json();
})
.cache(handlerError);
}
post(url,params = [],option = {}){
const options = Object.assign({
method: 'POST',
},option);
options.body = JSON.stringify(params);
return Http.staticFetch(url, options);
}
put(url,params = [],option = {}){
const options = Object.assign({
method: 'PUT',
},option);
options.body = JSON.stringify(params);
return Http.staticFetch(url, options);
}
get(url, option = {}){
const options = Object.assign({
method: 'GET',
},option);
Object.keys(option) && (url += '?' + qs.stringify(option));
return Http.staticFetch(url, options);
}
delete(url, option = {}){
const options = Object.assign({
method: 'DELETE',
},option);
Object.keys(option) && (url += '?' + qs.stringify(option));
return Http.staticFetch(url, options);
}
}
const resFun = new Http();
export default resFun;
user.js
import ajax from '../http';
export const userLogin = (params) => ajax.post('/api/user/login', params);
index.js
//webpack 的 require.context方法
const requireApi = require.context('.', true, /\.js$/);
const module = {};
requireApi.keys().forEach(key => {
if(key === './index.js' || key === './http.js') return;
Object.assign(module, requireApi(key));
});
export default module;