簡體   English   中英

"如何使用 axios 發出多個 api 請求"

[英]how to make multiple api request using 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;

請求.js

import apiService from '../apiService';

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


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

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

這與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'})
}

首先,不確定您是否要在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,
  });
}

我正在這樣工作。<\/strong> 你可以用這個<\/strong>

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM