繁体   English   中英

在React中为外部库(npm模块)添加自定义配置的位置

[英]Where to add custom configuration for external libraries(npm modules) in react

在哪里添加用于外部库(npm模块)的自定义配置,这将在整个应用程序中使用

我的问题陈述是:我正在使用axios进行api调用,我不想在每个调用中分别包含身份验证标头,我正在考虑创建一个文件并在那里导入axios并执行类似的操作

customAxios = axios
customAxios.defaults.headers.common['Authorization'] = store.getState().session.token;

export customAxios

现在我将在需要执行api调用的任何文件中导入customAxios这是正确的方法吗? 如果不是如何处理这种情况

顺便说一句,我是新来的反应

您可以在其构造函数中创建一个api类,可以创建axios实例并分配标头信息。 然后在所有调用中使用实例。

export default class Api{    
    constructor(auth_token){
        this.customAxios= axios.create({
            baseURL: 'https://myserverurl.com'
          });              
          this.customAxios.defaults.headers.common['Authorization'] = auth_token;            
    }

    getInfo(){
        this.customAxios.get('/info') ....// do further processing and return data
    }
}

当您要调用api时,您可以创建一个实例并将该实例用于您的调用。

let apiInstance = new Api(store.getState().session.token);
apiInstance.getInfo();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM