本文介绍了如何在axios.all方法React Native中分配标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要从多个api获取数据并将其渲染到<Pickers />中,但问题是我无法在此axios.all方法中为Auth分配标头.请为我提供解决方案或犯错.

I'm getting data from multiple api's and rendering into <Pickers /> but the issue is that I'm unable to assign headers for Auth in this axios.all method. Kindly provide me a solution or mistake if I'm doing.

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

推荐答案

您可以使用配置并创建实例来设置诸如url, token, timeout等的常见内容

You can use the configs and create instance to set common things like url, token, timeout etc

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中使用

This can be used in your component.jsx like

import {yourAPIcallMethod} from './httpService';

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

您可以在 github axios 上了解更多信息. a>.

You can see and learn more on github axios.

这篇关于如何在axios.all方法React Native中分配标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!