如何使用axios进行多个api请求

时间:2018-06-05 14:01:12

标签: javascript reactjs redux react-redux axios

我正在通过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;
  

Request.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
        });
    });
};

2 个答案:

答案 0 :(得分:0)

这根本与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'})
}

答案 1 :(得分:0)

首先,不确定是否要在componentWillMount中执行此操作,因为在完成所有这些操作之后,组件才会呈现,最好将它放在componentDidMount中,并且具有一些默认状态,这些状态将在完成这些请求后更新。其次,你想限制你写的setStates的数量,因为它们可能会导致额外的重新渲染,这是一个使用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,
  });
}