[英]Add Bearer type header in react native axios
我正在使用 react native axios 并尝试添加 Bearer 的标头类型。
它在邮递员中工作良好,因为:-
但它在我的代码中不起作用。 我的代码是:-
const axiosInstance = axios.create ({
//baseURL: process.env.VUE_APP_ROOT_API,
//timeout: 1000,
headers: {'Content-Type': 'application/json'},
});
axiosInstance.interceptors.request.use (
async function(config) {
console.log('config', config);
const token = await getUserAccessTokenFromStorage();
console.log('token in axios get',token);
if (token) config.headers.common = {'token': `Bearer ${token}`}; //try1
//if (token) config.headers.token = `Bearer ${token}`; //try2
return config;
},
function (error) {
return Promise.reject (error);
}
);
export const GET = async (url, params) => {
let getRes = await axiosInstance.get(
url,
params
);
if (getRes.status === 200) {
return {data: getRes.data, status: true};
} else {
return {message: getRes.data.message, status: false};
}
};
我能做些什么来解决这个问题?
谢谢!!!
您不是从 if 子句返回config
。 这段代码应该可以工作。
axiosInstance.interceptors.request.use(
async function(config) {
console.log("config", config);
const token = await getUserAccessTokenFromStorage();
console.log("token in axios get", token);
if (token) {
return {
...config,
headers: {
...config.headers,
token: `Bearer ${token}`
}
};
}
return config;
},
function(error) {
return Promise.reject(error);
}
);
PS:出于此类目的,您应该使用Authorization: Bearer <token>
标头。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.