123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309 |
- import Request from 'luch-request';
- import { baseUrl, apiPath } from '@/sheep/config';
- import $store from '@/sheep/store';
- import $platform from '@/sheep/platform';
- import {
- showAuthModal, cancelAutoSign
- } from '@/sheep/hooks/useModal';
- import AuthUtil from '@/sheep/api/member/auth';
- import {
- t
- } from '@/locale';
- const options = {
-
- showSuccess: false,
-
- successMsg: '',
-
- showError: true,
-
- errorMsg: '',
-
- showLoading: true,
-
- loadingMsg: t('common.loading'),
-
- auth: false,
-
- };
- let LoadingInstance = {
- target: null,
- count: 0,
- };
- function closeLoading() {
- if (LoadingInstance.count > 0) LoadingInstance.count--;
- if (LoadingInstance.count === 0) uni.hideLoading();
- }
- const http = new Request({
- baseURL: baseUrl + apiPath,
- timeout: 8000,
- method: 'GET',
- header: {
- Accept: 'text/json',
- 'Content-Type': 'application/json;charset=UTF-8',
- platform: $platform.name,
- "Accept-Language": uni.getStorageSync('userLanguage') || uni.getLocale(),
- },
-
- sslVerify: false,
-
-
-
- withCredentials: false,
-
- custom: options,
- });
- http.interceptors.request.use(
- (config) => {
-
- if (config.custom.auth && !$store('user').isLogin) {
- showAuthModal();
- return Promise.reject();
- }
-
- if (config.custom.showLoading) {
- LoadingInstance.count++;
- LoadingInstance.count === 1 &&
- uni.showLoading({
- title: config.custom.loadingMsg,
- mask: true,
- fail: () => {
- uni.hideLoading();
- },
- });
- }
-
- const token = getAccessToken();
- if (token) {
- config.header['Authorization'] = token;
- }
-
- config.header['Accept'] = '*/*'
- config.header['tenant-id'] = '1';
- config.header['terminal'] = '20';
-
- return config;
- },
- (error) => {
- return Promise.reject(error);
- },
- );
- http.interceptors.response.use(
- (response) => {
-
- if (response.config.url.indexOf('/member/auth/') >= 0 && response.data?.data?.accessToken) {
- $store('user').setToken(response.data.data.accessToken, response.data.data.refreshToken);
- }
-
- response.config.custom.showLoading && closeLoading();
-
- if (response.data.code !== 0) {
-
- if (response.data.code === 401) {
- cancelAutoSign()
- return refreshToken(response.config);
- }
-
- if (response.config.custom.showError) {
- cancelAutoSign()
- uni.showToast({
- title: response.data.msg || t('common.server_error_try_later'),
- icon: 'none',
- mask: true,
- });
- }
- }
-
- if (response.config.custom.showSuccess
- && response.config.custom.successMsg !== ''
- && response.data.code === 0) {
- uni.showToast({
- title: response.config.custom.successMsg,
- icon: 'none',
- });
- }
-
- return Promise.resolve(response.data);
- },
- (error) => {
- console.log("服务器开小差")
- cancelAutoSign()
- const userStore = $store('user');
- const isLogin = userStore.isLogin;
- let errorMessage = t('common.network_request_error');
- if (error !== undefined) {
- switch (error.statusCode) {
- case 400:
- errorMessage = t('common.request_error');
- break;
- case 401:
- errorMessage = isLogin ? t('common.login_expired') : t('common.please_login');
-
- break;
- case 403:
- errorMessage = t('common.access_denied');
- break;
- case 404:
- errorMessage = t('common.request_error');
- break;
- case 408:
- errorMessage = t('common.request_timeout');
- break;
- case 429:
- errorMessage = t('common.frequent_requests');
- break;
- case 500:
- errorMessage = t('common.server_error_try_later');
- break;
- case 501:
- errorMessage = t('common.server_unavailable');
- break;
- case 502:
- errorMessage = t('common.network_error');
- break;
- case 503:
- errorMessage = t('common.service_unavailable');
- break;
- case 504:
- errorMessage = t('common.network_timeout');
- break;
- case 505:
- errorMessage = t('common.http_not_supported');
- break;
- }
- if (error.errMsg.includes('timeout')) errorMessage = t('common.request_timeout');
-
- if (error.errMsg.includes('Network'))
- errorMessage = window.navigator.onLine ? t('common.server_exception') : t('common.check_network_connection');
-
- }
- if (error && error.config) {
- if (error.config.custom.showError === false) {
- uni.showToast({
- title: error.data?.msg || errorMessage,
- icon: 'none',
- mask: true,
- });
- }
- error.config.custom.showLoading && closeLoading();
- }
- return false;
- },
- );
- let requestList = []
- let isRefreshToken = false
- const refreshToken = async (config) => {
-
- if (config.url.indexOf('/member/auth/refresh-token') >= 0) {
- return Promise.reject('error')
- }
-
- if (!isRefreshToken) {
- isRefreshToken = true
-
- const refreshToken = getRefreshToken()
- if (!refreshToken) {
- return handleAuthorized()
- }
-
- try {
- const refreshTokenResult = await AuthUtil.refreshToken(refreshToken);
- if (refreshTokenResult.code !== 0) {
-
-
- throw new Error('刷新令牌失败');
- }
-
- config.header.Authorization = 'Bearer ' + getAccessToken()
- requestList.forEach((cb) => {
- cb()
- })
- requestList = []
- return request(config)
- } catch (e) {
-
-
- requestList.forEach((cb) => {
- cb()
- })
-
- return handleAuthorized()
- } finally {
- requestList = []
- isRefreshToken = false
- }
- } else {
-
- return new Promise((resolve) => {
- requestList.push(() => {
- config.header.Authorization = 'Bearer ' + getAccessToken()
- resolve(request(config))
- })
- })
- }
- }
- const handleAuthorized = () => {
- const userStore = $store('user');
- userStore.logout(true);
- showAuthModal();
-
- return Promise.reject({
- code: 401,
- msg: userStore.isLogin ? t('common.login_expired') : t('common.please_login')
- })
- }
- const getAccessToken = () => {
- return uni.getStorageSync('token');
- }
- const getRefreshToken = () => {
- return uni.getStorageSync('refresh-token');
- }
- const request = (config) => {
- return http.middleware(config);
- };
- export default request;
|