在反应中为外部库(npm 模块)添加自定义配置的位置
Where to add custom configuration for external libraries(npm modules) in react
react中外部库(npm模块)的自定义配置在哪里,整个app都会用到
我的问题陈述是:
我正在使用 axios 进行 api 调用,我不想在每个调用中单独包含身份验证 header,我正在考虑创建一个文件并在那里导入 axios 并执行类似这样的操作
customAxios = axios
customAxios.defaults.headers.common['Authorization'] = store.getState().session.token;
export customAxios
现在我将在我需要 api 调用的任何文件中导入 customAxios
这是正确的方法吗?如果不是这种情况如何处理
顺便说一句,我是新手
您可以创建一个 api class,在其构造函数中您可以创建一个 axios 实例并分配 header 信息。然后在所有调用中使用该实例。
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();
react中外部库(npm模块)的自定义配置在哪里,整个app都会用到
我的问题陈述是: 我正在使用 axios 进行 api 调用,我不想在每个调用中单独包含身份验证 header,我正在考虑创建一个文件并在那里导入 axios 并执行类似这样的操作
customAxios = axios
customAxios.defaults.headers.common['Authorization'] = store.getState().session.token;
export customAxios
现在我将在我需要 api 调用的任何文件中导入 customAxios 这是正确的方法吗?如果不是这种情况如何处理
顺便说一句,我是新手
您可以创建一个 api class,在其构造函数中您可以创建一个 axios 实例并分配 header 信息。然后在所有调用中使用该实例。
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();