I'm learning vuejs and nodejs to set up authentication for an upcoming student project.
For that I created an api that allows to create character cards that when clicked allow to see the history of the character.
It works well and so I attacked the authentication part where I managed to allow the creation of user and the connection of this last with jsonwebtoken and everything works on the backend side but when I am on the frontend side the access to the characters when the user is connected does not work and returns me an error that I wrote if nothing works. I want to specify that when I connect the token is well created because the backend returns it well with the user ID however when I arrive on the page of the characters and I look at the headers of the request I do not see "Authorization : Bearer token" . And I have no idea if on the frontend I'm supposed to do any other manipulation besides retrieving the list of characters.
I wondered if the problem didn't come from a npm "cors" package I had downloaded and rewrote the permissions for the request headers but nothing works.
I want to specify that I use axios to get my list of characters.
I can get the token on the login request but I don't know what to do with it to allow the user to access the characters
Here the unauthorized error when the login works and redirect to the character lists :
Here the authentication middleware from the backend :
Here my routes with auth middleware :
Sorry If I'm missing some things on how to write a good question here I'm not used to stackoverflow so If I have to give more specifics information tell me on comment
Thanks for reading
CodePudding user response:
You should set the authorization header for each requests requires authentication.
If you use custom axios instance for your requests, you can specify the authorization header using interceptors such as:
axiosInstance.interceptors.request.use(config => {
const token = /* your token */;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
Or, if you don't use such an instance, you can set it as:
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;