import axios from 'axios';
import Config from '../config/settings';
import {getStorageKey, KEYS, setStorageKey} from './storage';
const factory = new axios.create({
timeout: 30000,
baseURL: Config.BASE_URL,
headers: {
'App-Key': Config.APP_KEY,
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json',
},
});
factory.interceptors.request.use(
async (config) => {
try {
console.log(config.headers.Authorization);
const token = await getStorageKey(KEYS.TOKEN);
const appType = await getStorageKey(KEYS.THERAPY_TYPE);
if (!config.headers.Authorization && token) {
debugger;
config.headers.Authorization = `Bearer ${token}`;
}
if (!config.headers['App-Type'] && appType) {
config.headers['App-Type'] = appType;
}
console.log('config============');
console.log(config);
} catch (e) {
debugger;
console.log(e);
//Not logged in
}
return config;
},
(error) => {
return Promise.reject(error);
},
);
factory.interceptors.response.use(
(response) => response,
(error) => {
if (error.response && error.response.status === 401) {
setStorageKey(KEYS.IS_LOGGED_IN, false);
}
return Promise.reject(error.response ? error.response.data : error);
},
);
export default factory;
用的时候:
export const updateUserProfile = (user) => () => {
return new Promise(async (resolve, reject) => {
try {
apiFactory.post('/user/profile/update', {...user}).then(resolve, reject);
} catch (e) {
reject(e);
}
});
};
主要是觉得这个拦截器功能比较好用。
网友评论