I'm learning vuejs and nodejs to set up authentication for an upcoming student project.
To do this, I created an API that allows the creation of character cards that can be clicked to view the character's history.
It was working fine so I hacked the authentication part and I managed to allow user creation and concatenated the last one with jsonwebtoken and everything worked on the backend but when I'm on the frontend I can access the characters when the user Doesn't work when connected and returns an error I wrote if nothing works. I want to specify that when I connect, the token is created fine because the backend returns it fine with the user ID, but when I get to the characters page and look at the headers of the request, I don't see the "Authorization: Hold There is a "token". And I don't know if I should do anything else on the front end other than retrieving a list of characters.
I was wondering if the problem wasn't from the npm "cors" package I downloaded and rewrote the permissions in the request headers, but nothing worked.
I want to specify that I use axios to get my character list.
I can get the token in the login request but I don't know how to use it to allow the user to access the characters
This is an unauthorized error when logging in to work and redirecting to a character list:
Here is the authentication middleware from the backend:
This is my route using the authentication middleware:
Sorry if I missed something on how to write a good question here, I'm not used to stackoverflow so if I have to provide more specific information please let me know in the comments
Thank you for reading
P粉2741615932024-01-17 10:26:46
You should set the Authorization header for every request that requires authentication.
If you use a custom axios instance for your request, you can use an interceptor to specify the authorization header, for example:
axiosInstance.interceptors.request.use(config => { const token = /* your token */; if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; });
Alternatively, if you are not using such an instance, you can set it to:
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;