...
const userIcon = document.querySelector('.user-icon');
userIcon.addEventListener("click", () => {
if (token) {
fetch('/privatearea', {
headers: {
'authorization': `Bearer ${token}`
}
}).catch(err => console.log(err));
} else {
window.location.assign('/login');
}
...
What i'm trying to do is:
- When the element "userIcon" is clicked if "token" exists, i want to fetch the url "http://localhost:3000/privatearea".
- If token doesn't exist the url "http://localhost:3000/login" is reached.
...
router.get('/privatearea', authenticateToken, (req, res) => {
res.render("private-area");
});
...
The backend has been done with node js and express.
So, if i click the element the url "http://localhost:3000/privatearea" should be reached and the page "private-area" should be renderized.
But it doesn't happen. I don't need a response, but i would reach the url by setting some headers.
CodePudding user response:
fetch() by itself does not render anything in the browser. It just returns content back to your Javascript. So, if you had a .then() handler on the fetch() call, you would just get back the rendered data from res.render("private-area"); on your server.
userIcon.addEventListener("click", () => {
if (token) {
fetch('/privatearea', {
headers: {
'authorization': `Bearer ${token}`
}
}).then(data => {
// here you will see the result of res.render("private-area");
// on your server
console.log(data);
}).catch(err => console.log(err));
} else {
window.location.assign('/login');
}
...
}
So, the way you have it isn't the correct design for using fetch(). Since you don't show the larger context of this feature here, it's not entirely clear what the best architecture/solution would be here. Here are some options:
- You could take the
datafrom the.then()handler I show above and insert it into the current page using your own Javascript. - You could do
window.location = '/privatearea';and find some other way to communicate the Bearer token to your server (perhaps a previous call to your server sets a session cookie) so your server can use the session cookie to verify that the browser is allowed to enter/privatearea. - You could switch your auth model to something that is more friendly to browser URLs (like a session/cookie) since you can't use a Bearer Token from a URL entered into the browser bar as they can only be used from Javascript. The user logs in, gets assigned a session cookie and URL handlers on your server for URLs from the browser check that.
