如何在 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));

您可以创建一个服务文件来处理 GET 或 POST 的所有请求,用于处理带有身份验证标头的 GET 请求的 file 被赋予 belwo

获取服务.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);
}
}    

您可以使用配置并创建实例来设置常见内容,例如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")
}
}

这可以用于您的组件.jsx,例如

import {yourAPIcallMethod} from './httpService';
async componentDidMount(){
const data = await yourAPIcallMethod();
this.setState({One: data.One, Two: data.Two})
}

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

最新更新