首页 > 解决方案 > 如何在 axios.all 方法 React Native 中分配标头

问题描述

我正在从多个 api 获取数据并渲染到<Pickers />其中,但问题是我无法在此axios.all方法中为 Auth 分配标头。如果我这样做,请给我一个解决方案或错误。

axios.all([
        axios.get(this.apiUrl + '/case/GetCaseType'),
        axios.get(this.apiUrl + '/case/GetCasePriority')
    ], { headers: { 'authorization': 'bearer ' + this.state.jwtToken } })
        .then(axios.spread(( response2, response3) => {
            console.log('Response 1: ', response1.data.retrn);
            console.log('Response 2: ', response2.data.retrn);
            console.log('Response 3: ', response3.data.retrn);
            this.hideLoader();
        })).catch(error => console.log(error.response));

标签: reactjsreact-nativeaxios

解决方案


您可以使用配置并创建实例来设置常见的东西,如url, token, timeout

import axios from 'axios';
const http = axios.create({
      baseURL: this.url,
      timeout: 5000
});

http.defaults.headers.common['authorization'] = `bearer ${this.state.jwtToken}`

export async function yourAPIcallMethod(){
   try{
       const [res1,res2] = await http.all([getOneThing(), getOtherThing()]);
       //when all responses arrive then below will run
       //res1.data and res2.data will have your returned data
       console.log(res1.data, res2.data)
       //i will simply return them
       return {One: res1.data, Two: res2.data}
      }
   catch(error){
      console.error(error.message || "your message")
      }
}

这可以在您的 component.jsx 中使用,例如

import {yourAPIcallMethod} from './httpService';

async componentDidMount(){
    const data = await yourAPIcallMethod();
    this.setState({One: data.One, Two: data.Two})
}

您可以在github axios上查看和了解更多信息。


推荐阅读