React教程(五) : Axios 基础应用

安装:
npm install axios --save

新建TUAPI.js

import axios from 'axios';
export const TUAPI = axios.create({
    baseURL: process.env.REACT_APP_BASE_URL,
    responseType: 'json'
});


// Add a request interceptor
TUAPI.interceptors.request.use(function (config) {
    // Do something before request is sent
    debugger;
    let baseURL = process.env.REACT_APP_BASE_URL;
    return config;
}, function (error) {
    // Do something with request error
    return Promise.reject(error);
});

// Add a response interceptor
TUAPI.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    debugger;
    return response;
}, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
});

通常我们会在API对象上面再包装一层Service对象,比如:

//CHANGE_PASSWORD是TUAPI对象中export出来的一个常量,指向对应的REST API地址
import { CHANGE_PASSWORD, TUApi } from './TUApi';
class LoginService {
  ......................

  changePassword(oldPassword: string, newPassword: string): Promise<void> {
    return TUApi.post(CHANGE_PASSWORD, { oldPassword, newPassword });
  }

  ......................
}

export const loginService = new LoginService();
posted @ 2020-11-03 21:40  老胡Andy  阅读(235)  评论(0编辑  收藏  举报