axios
import axios from 'axios';
import qs from 'qs';
switch (process.env.NODE_ENV) {
case 'production':
axios.defaults.baseURL = "api.abcdef.com";
break;
case 'test':
axios.defaults.baseURL = "192.168.20.21";
break;
default:
axios.defaults.baseURL = "127.0.0.1"
}
axios.defaults.timeout = 10000;
axios.defaults.withCredentials = true;
axios.defaults.headers['Content-Type'] = 'application/x-www-urlencoded';
axios.defaults.transformRequest = data => {
qs.stringify(data);
};
axios.interceptors.request.use(config => {
const token = localStorage.getItem('token');
config.headers.Authorization = token;
return config;
}, err => {
return Promise.reject(err);
})
axios.defaults.validateStatus = status => {
return /^(2|3)d{2}$/.test(status);
}
axios.interceptors.response.use(res => {
return res.data;
}, err => {
let { response } = err;
if (response) {
switch (response.status) {
case 401:
break;
case 403:
break;
case 404:
break;
}
} else {
if (!window.navigator.onLine) {
return;
} else {
return Promise.reject(err);
}
}
})
export default axios;
fetch
import qs from 'qs';
let baseURL = '';
switch (process.env.NODE_ENV) {
case 'production':
baseURL = "api.abcdef.com"
break;
case 'test':
baseURL = "192.168.0.0.1";
break;
default:
baseURL = "127.0.0.1";
break;
}
export default (url, options = {}) => {
url = baseURL + url;
!options.method ? options.method = 'GET' : null;
if (options.hasOwnProperty('params')) {
if (/^(GET|DELETE|HEAD|OPTIONS)$/i.test(options.params)) {
const ask = url.includes('?') ? '&' : '?';
url + `${ask}${qs.stringify(params)}`;
}
delete options.params;
}
options = Object.assign({
credentials: 'include',
headers: {}
}, options);
options.headers.Accept = "application/json";
const token = localStorage.getItem('token');
options.headers.Authorization = token;
if (/^(POST|PUT)$/i.test(options.method)) {
!options.type ? options.type = 'urlencoded' : null;
if (options.type === 'urlencoded') {
options.headers['Content-Type'] = 'application/x-www-urlencoded';
options.body = qs.stringify(options.body);
}
else if (options.type === 'json') {
options.headers['Content-Type'] = 'application/json';
options.body = JSON.stringify(options.body);
}
}
return fetch(url, options).then(res => {
if (!/^(2|3)d{2}$/.test(res.status)) {
switch (res.status) {
case 401:
break;
case 404:
break;
default:
break;
}
return Promise.reject(res);
}
return res.json();
}).catch(err => {
if (!window.navigator.onLine) {
return;
}
return Promise.reject(err);
})
}