何处为反应中的外部库(npm模块)添加自定义配置

时间:2017-10-01 12:33:46

标签: reactjs axios

在react中为外部库(npm模块)添加自定义配置的位置,将在整个应用程序中使用

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

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

export customAxios

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

顺便说一句,我是新手做出反应

1 个答案:

答案 0 :(得分:0)

您可以在其构造函数中创建一个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();