vue+react封装请求

import axios from 'axios'
import { Toast } from 'vant'
//开发环境
// const urlHost='https://localhost:9033'
// create an axios instance
const request = axios.create({
  // baseURL: urlHost, // url = base url + request url
  withCredentials: false, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
})

var that=this
// request interceptor
request.interceptors.request.use(
  config => {
    config.headers['jnpf-origin'] = 'pc'
    return config
  },
  error => {
    // do something with request error
    if (process.env.NODE_ENV === 'development') {
      console.log(error) // for debug
    }
    return Promise.reject(error)
  }
)

// response interceptor
request.interceptors.response.use(
  response => {
    const res = response.data 
    // console.log('====',response)
    if (response.status == 200) {
      return res
    }else{
      console.log('====',res)
      Toast(res.errmsg,)
      return res.msg
    }
  },
  error => {
    if (process.env.NODE_ENV === 'development') {
      console.log(error) // for debug
    }
    Toast(error|| '请求出错,请重试',)
    return Promise.reject(error)
  }
)

export default request
export {urlHost}
import axios from 'axios';

const instance = axios.create({
  baseURL: ' // 设置请求的基础URL
  timeout: 5000, // 设置请求超时时间
});
import instance from './axios';

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 在请求发送前添加请求头
    config.headers['Authorization'] = 'Bearer ' + localStorage.getItem('token');
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response) => {
    // 在响应返回后进行一些额外的处理
    return response;
  },
  (error) => {
    // 处理一些错误,如网络错误、服务器错误等
    return Promise.reject(error);
  }
);

export default instance;

你可能感兴趣的:(javascript,前端,vue.js)