React Axios

2020-11-06  本文已影响0人  kevin5979

安装

yarn add axios

config.js

export const TIMEOUT = 10000;

const devBaseURL = "https://httpbin.org";
const proBaseURL = "https://production.org";
console.log(process.env.NODE_ENV);
export const baseURL = process.env.NODE_ENV === 'development' ? devBaseURL: proBaseURL;

request.js

import axios from 'axios';

import {
  TIMEOUT,
  baseURL
} from "./config";

const instance = axios.create({
  timeout: TIMEOUT,
  baseURL: baseURL
})

axios.interceptors.request.use(config => {
  // 1.发送网络请求时,在页面中添加一个loading组件作为动画;

  // 2.某些网络请求要求用户必须登录,可以在请求中判断是否携带了token,没有携带token直接跳转到login页面;

  // 3.对某些请求参数进行序列化;
  return config;
}, err => {
  return err;
})

instance.interceptors.response.use(response => {
  return response.data;
}, err => {
  if (err && err.response) {
    switch (err.response.status) {
      case 400:
        err.message = "请求错误";
        break;
      case 401:
        err.message = "未授权访问";
        break;
    }
  }
  return err;
})

export default instance;

使用

import request from "service/request"
request({
      url: "/get",
      params: {
        name: "zs",
        age: 18
      }
    }).then(console.log).catch(console.error);

    request({
      url: "/post",
      method: "post",
      data: {
        name: "ls",
        age: 20
      }
    }).then(console.log).catch(console.error);
END
上一篇下一篇

猜你喜欢

热点阅读