reactjs - 如何在 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));
解决方案
您可以使用配置并创建实例来设置常见的东西,如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上查看和了解更多信息。
推荐阅读
- java - 我可以在导入的库中为 bean 设置属性吗?
- mesibo - Mesibo -- 已关闭 On-Premise 但仍将 webhook 调用转到 On-Premise IP
- java - 如何在改造 android 中更改 json 顺序?
- ipaf - 使用 PAF 生成 pdf 文件
- ios - 为什么 Swift 5.0.1 和 5.3.2 之间的错误运行时多态性不同
- flutter - 如何根据颤动中的ID从列表中获取项目?
- python - 在 csv pandas 中添加特定消息
- pytorch - 如何将配置有小的 max_position_embeddings 的预训练变压器模型扩展到更长的模型
- javascript - 如何将图像从反应本机上传到java spring boot?
- project-reactor - 像 flatMap() 这样在同一主线程上运行的 Reactor 运算符是否比常规阻塞代码更有效?