execute async function on page loading with express-handlebars

40 Views Asked by At

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:

  1. use also document instead of window
  2. Use load and loadstart events
  3. 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: enter image description here

0

There are 0 best solutions below