Search code examples
javascriptnode.jsexpressexpress-session

res.sendFile is being aborted, sending me to localhost:XXXX/?


I have a route set up that is being accessed, as I know from the console.logs. However, The res.sendFile at the end is not taking it to the correct place. It sends me to localhost:XXXX/?.

This is the route:

router.get('/bidder', async (req, res) => {
  console.log('GET /bidder')
  console.log(req.session.user_id)
  
  try {
    const userData = await User.findByPk(req.session.user_id, {
      attributes: { exclude: ['password'] },
      include: [
        { 
          model: Project,
          attributes: ['project_name'],
          through: Bid,
          as: 'project_users'
        }
      ],
    });

    console.log(path.join(__dirname, '/../public', '/bidder.html'))
    res.sendFile(path.join(__dirname, '/../public', '/bidder.html',), function (err) {
      if (err) {
        console.log(err)
      }
    })
  } catch (err) {
    console.log(err)
    res.status(500).json(err);
  }
});

And this is the route that gets me to the /bidder route above:

router.post('/login', async (req, res) => {
  console.log('POST /login');
  try {
      const user = await User.findOne({ where: { email: req.body.email } });

      if (!user) {
          res
              .status(400)
              .json({ message: 'Incorrect email or password, please try again.' });
          return;
      }

      const validPassword = await user.checkPassword(req.body.password);

      if (!validPassword) {
          res
              .status(400)
              .json({ message: 'Incorrect email or password, please try again.' });
          return;
      }

      req.session.save(() => {
        console.log(user);
        console.log(user.id);
        console.log(user.is_poster);
        
        req.session.user_id = user.id;
        req.session.is_poster = user.is_poster;
        req.session.logged_in = true;
        
        console.log(req.session.logged_in)
        
        if (req.session.is_poster == false) {
          console.log('---------------------------')
          console.log(req.session.is_poster)
          console.log(path.join(__dirname, '/../public/bidder.html'))
          
          res.redirect('/bidder')
        } else if (req.session.is_poster == true) {
          console.log('---------------------------')
          console.log(req.session.is_poster)
          console.log(path.join(__dirname, '/../public/poster.html'))
          
          res.redirect('/poster')
        } else {
          console.log('not logged in')
          
          res.redirect('/')
        }
      });

  } catch (err) {
    console.log(err);
    res.status(404).end();
  }
});

The error that it is logging is:

Error: Request aborted
    at onaborted (C:\Users\camer\Desktop\homework\project-bid-board\node_modules\express\lib\response.js:1025:15)
    at Immediate._onImmediate (C:\Users\camer\Desktop\homework\project-bid-board\node_modules\express\lib\response.js:1067:9)
    at processImmediate (internal/timers.js:464:21) {
  code: 'ECONNABORTED'
}

If I just type localhost:XXXX/bidder into the browser, it sends me to the correct html page, as it should.

EDIT This is the JS associated with submitting the data for login:

$('#login-button').on('click', function(event) {
    event.preventDefault();
    
    var email = $('#login-email').val()
    var password = $('#login-password').val()

    loginUser(email, password)
})

const loginUser = async (email, password) => {
    const response = await fetch (`/api/user/login`, {
        method: 'POST',
        body: JSON.stringify({ email, password }),
        headers: { 'Content-Type': 'application/json' },
    })

    console.log(response.statusText)
}

And this is the form it is handling:

                  <form>
                    <div>
                        <label for="username">E-mail / Username:</label>
                        <input class="text-input" id="login-email" type="text" placeholder="[email protected]" />
                    </div>
                    <div>
                        <label for="password">Password:</label>
                        <input class="text-input" type="text" id="login-password" placeholder="password"></input>
                    </div>
                    <section>
                        <button class="btn-lg btn-block" id="login-button">Login</button>
                        <div class="text-center" id="signupSuccessMsg"></div>
                    </section>
                </form>

Solution

  • You are posting the /login with fetch() in your Javascript. fetch() by itself does NOT change ANYTHING in the browser window - even if the response is a redirect.

    Instead, fetch() makes an http request to your server and gets the response and delivers that to your Javascript. It is entirely up to your Javascript to decide what to do with that response. If you want to follow a redirect, then you have to write your Javascript to look for a 3xx response status from the fetch() call, get the location header and then set window.location to that new URL. That will then cause the browser to go to that new page.


    Since your Javascript that's posting the login form doesn't seem to be doing anything special, you could just remove your Javascript and let the browser post the form on its own and make sure your server was programmed to accept the way the form would be encoded if posted directly by the browser. Then, the browser WOULD follow the redirect response automatically or would display any content that the post returned.