I am looking to fetch data from my server controller using express handlebars. I created a simple controller to get the data from the request object - session, fetching this after being logged in. The controller:
const getUserController = async (req, res, next) => {
try {
const user = req.session.userData;
if (!user) {
console.log('Not found');
}
else {
return user;
}
}
catch (error) {
res.redirect('error', { message: 'Unexpected error in get user controller' });
}
}
In my express partial, I want to get the user data from my session. I created a simple event listener that I attached to the window, I used 'DOMContentLoaded' and async callback to get the user.
window.addEventListener('DOMContentLoaded', async (event) => {
//get the main user data
const userData = await fetch('/user-session', { method: 'GET' });
console.log('userData');
alert('Page loaded')
if (userData.ok) {
const user = await userData.json();
console.log('User'+ user)
}
});
What I tried:
- use also document instead of window
- Use load and loadstart events
- Use than/catch instead of async await
If I fetch this in the browser, it works....
I have the call in the network tab, but the request is on pending:
