123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- import axios from 'axios';
- import store from '@/store';
- import ENV_CONFIG from '@/config/env.js'
- import {
- getToken
- } from '@/utils/auth';
- const BASEHost = process.env.NODE_ENV === 'development' ? 'api' : window.location.origin;
- const service = axios.create({
- baseURL: BASEHost,
- timeout: 30000
- });
- // 请求拦截器
- service.interceptors.request.use(
- (config) => {
- config.headers['Content-Type'] = 'application/json';
- return config;
- },
- (error) => {
- return Promise.reject(error);
- }
- );
- // 响应拦截器
- service.interceptors.response.use(
- (response) => {
- const res = response.data;
- const {
- code,
- status,
- message,
- error
- } = res;
- if (code === 404) {
- uni.showToast({
- title: '请求的资源不存在',
- icon: 'error',
- duration: 3 * 1000
- });
- return Promise.reject(new Error(message || 'Error'));
- }
- // 返回数据失败
- if (status === 0) {
- uni.showToast({
- title: error,
- icon: 'error',
- duration: 3 * 1000
- });
- return Promise.reject(new Error(`${response.config?.params?.MethodName} ${error}` || 'Error'));
- }
- // 无效的操作用户
- if (status === -1) {
- uni.showToast({
- title: error,
- icon: 'error',
- duration: 3 * 1000
- });
- store.dispatch('user/signOut');
- window.location.href = '/';
- }
- return res;
- },
- (error) => {
- if (error.code === 'ERR_CANCELED') {
- return uni.showToast('取消上传成功');
- }
- uni.showToast({
- title: error.message,
- icon: 'error',
- duration: 3 * 1000
- });
- return Promise.reject(error);
- }
- );
- /**
- * 得到必需的请求参数
- * @returns {object} 返回必需的请求参数
- * */
- function getRequestParams() {
- const token = getToken();
- let access_token = token?.access_token ?? '';
- if (access_token == "") {
- uni.getStorage({
- key: 'AccessToken',
- success: function(res) {
- access_token = res.data;
- }
- });
- }
- return {
- AccessToken: access_token,
- UserCode: token?.user_code ?? '',
- UserType: token?.user_type ?? '',
- SessionID: token?.session_id ?? ''
- };
- }
- /**
- * @description http 请求封装
- */
- export const http = {
- /**
- * @param {String} url 请求地址
- * @param {object} config 请求配置
- */
- get: (url, config) => service.get(url, config),
- /**
- * @param {string} url 请求地址
- * @param {object} data 请求数据
- * @param {object} config 请求配置
- */
- post: (url, data = {}, config = {}) => {
- config.params = {
- ...config.params,
- ...getRequestParams()
- };
- return service.post(url, data, config);
- },
- postForm: (url, data = {}, config = {}) => {
- config.params = {
- ...config.params,
- ...getRequestParams(),
- };
- return service.postForm(url, data, config);
- },
- put: (url, data, config) => service.put(url, data, config),
- delete: (url, data, config) => service.delete(url, data, config)
- };
|