Skip to content

Instantly share code, notes, and snippets.

@loveyunk
Created July 1, 2018 02:07
Show Gist options
  • Save loveyunk/3c3a5014ad94d103e5a87ed86fb19149 to your computer and use it in GitHub Desktop.
Save loveyunk/3c3a5014ad94d103e5a87ed86fb19149 to your computer and use it in GitHub Desktop.
request.js
import axios from 'axios';
import config from './config';
const {ERR_OK, BASE_URL_PRO, BASE_URL_DEV} = config;
const baseURL = process.env.NODE_ENV === 'development'
? BASE_URL_DEV
: BASE_URL_PRO;
/**
* Create an Axios Client with defaults
*/
const client = axios.create({
// `baseURL` will be prepended to `url` unless `url` is absolute. It can be
// convenient to set `baseURL` for an instance of axios to pass relative URLs to
// methods of that instance.
baseURL: baseURL,
// `timeout` specifies the number of milliseconds before the request times out.
// If the request takes longer than `timeout`, the request will be aborted.
// timeout: 5000,
headers: {
// 'content-type': 'application/json'
}
});
/**
* Request Wrapper with default success/error actions
*/
const request = function (options) {
// 数据请求成功
const onSuccess = function (response) {
console.debug('Request Successful!', response);
return response.data;
};
// 数据请求失败
const onError = function (error) {
console.error('Request Failed:', error.config);
if (error.response) {
// Request was made but server responded with something other than 2xx
console.error('Status:', error.response.status);
console.error('Data:', error.response.data);
console.error('Headers:', error.response.headers);
} else {
// Something else happened while setting up the request triggered the error
console.error('Error Message:', error.message);
}
return Promise.reject(error.response || error.message);
};
// 统一处理后端错误
const onPrompt = function (response) {
if (response.retCode === ERR_OK) {
return response;
} else {
// TODO:
}
};
return client(options)
.then(onSuccess)
.then(onPrompt)
.catch(onError);
};
export default request;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment