Skip to content

Instantly share code, notes, and snippets.

@wisetc
Created August 31, 2019 01:31
Show Gist options
  • Save wisetc/d6f528a3a02d49b13a999e21f8fd1087 to your computer and use it in GitHub Desktop.
Save wisetc/d6f528a3a02d49b13a999e21f8fd1087 to your computer and use it in GitHub Desktop.
Make axios instance.
import { Toast } from 'saltui';
import Axios from 'axios';
import env from 'src/env';
export const requestHeaders = { 'Content-Type': 'application/json' };
export const transformRequest = (data = {}, headers) => {
if (typeof data === 'string') return data;
return JSON.stringify(data);
};
export const responseInterceptor = response => response;
export const exceptionInterceptor = error => {
const status = error.response ? error.response.status : '';
const dict = {
404: '服务暂不可用',
500: '服务内部错误',
};
Toast.show({
type: 'error',
content: dict[status] || '服务暂不可用',
});
return Promise.reject(error);
};
export function createAxios(baseURL, options = {}, serviceName = '') {
let _axios = Axios.create({
baseURL,
headers: requestHeaders,
transformRequest: [transformRequest],
timeout: 10000,
...options,
});
let _exceptionInterceptor = null;
if (serviceName) {
_exceptionInterceptor = error => {
const response = error.response;
let tip = '故障';
if (!response) {
tip = '没响应';
} else {
const status = response ? response.status : 0;
tip = status === 404 ? '不在了' : `[${status}] 不给力`;
}
Toast.show({
content: '抱歉~ ' + serviceName + tip,
duration: 5000,
});
return Promise.reject(error);
};
}
_axios.interceptors.response.use(
responseInterceptor,
_exceptionInterceptor || exceptionInterceptor
);
return _axios;
}
export function getBaseURL(serviceDevHost, servicePort, serviceID) {
if (env === 'dev') {
return 'http://192.168.1.33:7000/' + serviceID;
// return `http://${serviceDevHost}:${servicePort}/` + serviceID;
} else if (env === 'test') {
return 'http://testapi.example.com/' + serviceID;
} else {
return 'http://api.example.cn/' + serviceID;
}
}
@wisetc
Copy link
Author

wisetc commented Feb 14, 2020

// env.js
/** @typedef {'dev' | 'test' | 'staging' | 'prod'} ENV */

/**
 * @returns {ENV}
 */
export function getEnv() {
  const hostname = window.location.hostname
  /** @type {Map<string, ENV>} */
  const hostnameMap = new Map([
    ['localhost', 'dev'],

    ['webtest.company.cn', 'test'],

    ['h5test.company.cn', 'staging'],
    ['ty.company.cn', 'staging'],

    ['h5.company.cn', 'prod'],
    ['yueyu.pay.company.cn', 'prod'],
  ])
  return hostnameMap.has(hostname) ? hostnameMap.get(hostname) : 'dev'
}

export default getEnv()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment