I found two instances of localhost in the developer tools network tab. So when navigating to '/', the first entry is of type 'document' with localhost, and the second entry is of type 'xhr' also with localhost. I noticed that only the second type contains the token value in the request headers.
server.js
app.get('/', loginRequired, (req, res) => { res.sendFile(__dirname +'/views/index.html'); });login-required.js
const jwt = require('jsonwebtoken');const loginRequired = async (req, res, next) => { // TEST CODE const userToken = req.headers["authorization"]?.split('')[1]; console.log(userToken +' TEST===1'); // if(userToken) { <= The page experiences infinite loading when using this logic. // next(); <= (userToken === undefined) // } next() // undefined value and the actual token **sequence are printed in the console.**}module.exports = loginRequired;test.js (front)
const userToken = localStorage.getItem('token');if (userToken) { const headers = { authorization: `Bearer ${userToken}`, }; axios.get('/', { headers, withCredentials: true }) .then(response => { // console.log(response.data); }) .catch(error => { console.error(error); });} else { // Handle case when token doesn't exist}test.js is linked to index.html via a script tag.
The cause I am considering is as follows.
(1) Send a GET request to ('/').
(2) The server executes loginRequired.
(3) loginRequired is executed while not receiving HTML from the server, resulting in the token value becoming undefined.
(4) After passing through next(), the server responds with HTML from the client.
(5) Display the HTML in the browser and load the JavaScript associated with that HTML.
(6) At this point, the loaded JavaScript retrieves the logic of sending a GET request (/) and retrieves the token value again from the server.js as a response to loginRequired.
In other words, the JavaScript needs to be loaded in order to retrieve the userToken from local storage and make a request to fetch the token value.
However, shouldn't token validation and authorization occur before the GET request, ensuring that the HTML is loaded only after permission is granted?
I need your advice. Thank you.