Reputation: 605
I am using react native axios and trying to add header type of Bearer.
Its working good in postman as:-
but it is not working in my code. My code is:-
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};
}
};
What can I do to resolve this?
Thanks!!!
Upvotes: 0
Views: 311
Reputation: 9713
You are not returning config
from if clause. This code should work.
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: You should use Authorization: Bearer <token>
header for such purposes.
Upvotes: 2