How to assign headers in axios.all method React Native

坚强是说给别人听的谎言 提交于 2020-01-16 11:58:11

问题


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

回答1:


You can create a service file to handle all request for GET or POST, FIle for handling GET request with Autherization header is given belwo

GetService.js

import axios from 'axios'; 
let constant = {
    baseurl:'https://www.sampleurl.com/'
};
let config = {    
    headers: {
    'Content-Type': 'multipart/form-data',
    'Accept': 'application/json'
    }
};

export const GetService = (data,Path,jwtKey) => {
    // jwtKey is null then get request will be send without header, ie for public urls
    if(jwtKey != ''){
        axios.defaults.headers.common['Authorization'] = 'Bearer '+jwtKey;
    }

    try{
        return axios.get(
                            constant.baseUrl+'api/'+Path, 
                            data, 
                            config
                        );
    }catch(error){
        console.warn(error);
    }
}    



回答2:


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

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

You can see and learn more on github axios.



来源:https://stackoverflow.com/questions/59243785/how-to-assign-headers-in-axios-all-method-react-native

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!