【问题标题】:how to make multiple api request using axios如何使用 axios 发出多个 api 请求
【发布时间】:2018-06-05 14:01:12
【问题描述】:

我在我的 react 应用程序中有通过 axios 进行 api 调用的现有服务,我认为这一次仅限于一个 api 请求,我想使用 axios.all 发出多个请求,但我无法找到修改服务的方法,请参见下面的代码

在 Action.js 中,您可以看到我合并了两个请求,我想这是错误的,请帮助我如何使用 axios.all 合并两个请求,并建议 api 服务实现是正确的,或者我该怎么做改进一下

APIService.js

import axios from 'axios';
import apiConfig from './apiConfig';
import UserSession from './userSession';
import history from '../utils/history/history';

const session = sessionStorage;

var axiosConfig = axios.create({
                  baseURL: apiConfig.baseUrl,
                  headers: {
                    Authorization: sessionStorage.getItem('token') != null ? 
                    `Bearer ${sessionStorage.getItem('token')}` : null,
                    Accept: 'application/json',
                   'Content-Type': 'application/json'
                  },
                timeout: 20000,
                responseType: 'json'
              });

 axiosConfig.interceptors.request.use((config) => {
    config.headers.Authorization =
        sessionStorage.getItem('token') != null ? `Bearer 
        ${sessionStorage.getItem('token')}` : null;
    return config;
 },(error) => Promise.reject(error));

const apiService = function(options) {
 const onSuccess = function(response) {
    if (response.status === 201) {
        return Promise.resolve(
            Object.assign(
                {},
                {
                    message: response.statusText
                }
            )
        );
    } else if (response.status === 200) {
        if ((response.data && response.data !== null) || response.data !== 
             undefined || response.data !== '') {
            return response.data;
        } else {
            return Promise.resolve(
                Object.assign(
                    {},
                    {
                        message: response.statusText
                    }
                )
            );
        }
    } else if (response.data.length < 1) {
        return Promise.reject(
            Object.assign(
                {},
                {
                    message: 'No Data'
                }
            )
        );
    } else {
        return response.data;
    }
};

const onError = function(error) {
    if (error.response) {
        if (error.response.status === 401) {
            sessionStorage.removeItem('token');
            window.location = '/login';
            return Promise.reject(error.response);
        } else if (error.response.status === 404) {
            return Promise.reject(
                Object.assign(
                    {},
                    {
                        message: error.response.statusText
                    }
                )
            );
        } else if (error.response.status === 500) {
            return Promise.reject(
                Object.assign(
                    {},
                    {
                        message: error.response.statusText
                    }
                )
            );
        } else {
            return Promise.reject(error.response.data);
        }
    } else if (error.request) {
        // The request was made but no response was received

        return Promise.reject(
            Object.assign(
                {},
                {
                    message: error.message
                }
            )
        );
        //return Promise.reject(error.message);
    } else {
        // Something else happened while setting up the request
        // triggered the error
        return Promise.reject(
            Object.assign(
                {},
                {
                    message: error.message
                }
            )
        );
    }
};

return axiosConfig(options).then(onSuccess).catch(onError);
};

export default apiService;

请求.js

import apiService from '../apiService';

export const FirstRequest = () => {
  return apiService({
    url: 'FirstURL',
    method: 'get',
  });
};


export const SecondRequest = () => {
  return apiService({
    url: 'SecondURL',
    method: 'get',
  });
};

Action.js

export const SomeHandler = () => (dispatch) => {
   dispatch({
    type: API_REQUEST
   });

 FirstRequest()
    .then((res) => {
        dispatch({
            type: API_SUCCESS
        });
         SecondRequest().then((res) => {
            dispatch({
              type: API_SUCCESS
            });
            dispatch({ type: VIEW1, payload: res });
          dispatch({ type: VIEW2, payload: res });
           }).catch((err) => {
           dispatch({
            type: API_FAILURE,
            payload: err
           });
        });


    })
    .catch((err) => {
        dispatch({
            type: API_FAILURE,
            payload: err
        });
    });
};

【问题讨论】:

    标签: javascript reactjs redux react-redux axios


    【解决方案1】:

    这与 axios 完全无关。您可以使用 async 库将两个异步函数组合在一个操作方法中:

    async.parallel([
        getUsers,
        getComments
    ],
    function(err, results) {
        // the results array will equal to [[], {'x': 'y'}] even though
        // the second function had a shorter timeout.
        // dispatch here
    });
    
    function getUsers(callback) {
        callback(null, [])
    }
    
    function getComments(callback) {
        callback(null, {'x': 'y'})
    }
    

    【讨论】:

      【解决方案2】:

      首先,不确定你是否想在你的 componentWillMount 中执行此操作,因为在所有这些完成之前你的组件不会呈现,最好将它放在 componentDidMount 中并有一些默认状态,一旦完成这些请求就会更新。其次,您想限制您编写的 setState 的数量,因为它们可能会导致额外的重新渲染,这是使用 async/await 的解决方案:

      async componentDidMount() {
        const firstRequest = await axios.get(URL1);
        const secondRequest = await axios.get(URL2);
        const thirdRequest = await axios.get(URL3);
      
        this.setState({
          p1Location: firstRequest.data,
          p2Location: SecondRequest.data,
          p3Location: thirdRequest.data,
        });
      }
      

      【讨论】:

      • 但我不想将 api url 暴露给组件,它们应该在一些配置文件中管理,并且调用也应该单独维护,如您在上面的代码中看到的那样
      【解决方案3】:

      我就是这样工作的。你可以用这个

       const token_config = {
       headers: {
          'Authorization': `Bearer ${process.env.JWD_TOKEN}`
         }
       }
      
      const [ res1, res2 ] =  await Axios.all([
          Axios.get(`https://api-1`, token_config), 
          Axios.get(`https://api-2`, token_config)
        ]);
      
        res.json({
          info: {
            "res_1": res1,
            "res_2": res2
          }
        });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-23
        • 2020-09-26
        • 2020-11-05
        • 1970-01-01
        • 2021-06-30
        • 2022-11-02
        • 2021-11-12
        • 2022-10-08
        相关资源
        最近更新 更多