node.jsexpressauthenticationsendfileserving

html file does not appear after logging without any error


I am new to server-side programming. I am trying to serve a HTML file (mapview.html) after authentication ,but it does not appear without any error. there is no problem with authentication process. I expect when I click on login button, the codes check req data and after validating, mapview.html pop up but nothing happen. res.sendFile() causes in jquery part, console.log(res), get me all html codes in console line of chrome.


files directory:

src
 index.js
 db 
 public 
   index.html
   mapview.html
 middleware 
   auth.js
 routers 
   user
   task
 model
   user
   task

index.html

  $('div[name="logIn"]').click( () => { // select a div element that its name is logIn
      console.log('LOG-IN:')                 

      $.ajax({
           url: '/login',
           data: $('#loginForm').serialize(), // Get email and pass from login form 
           type: 'POST',
           success: function (res) {                                      
                console.log(res)                       
           }   
      })

  })

user.js

router.post('/login', async (req, res) => {

  try {
    const user = await User.findByCredentials(req.body.email, req.body.password)
    const token = await user.generateAuthToken()        

    const publicDir = path.join(__dirname, '../public')          
    res.sendFile(path.join(publicDir + '/mapview.html'));

  } catch (e) {         
     res.status(400).send(e)
  }
})

index.js

 const express = require('express');
 require('./db/mongoose'); 
 const bodyParser = require('body-parser');
 const userRouter = require('./routers/user');
 const taskRouter = require('./routers/task');  

 const app = express();
 const port = process.env.PORT || 3000; 

 app.use(express.json()); // Parse recieved json body  data from Postman

 app.use(bodyParser.urlencoded({extended: true}));
 app.use(bodyParser.json());
 app.use(express.static(__dirname + '/public'));  

 app.use(userRouter); 
 app.use(taskRouter);   

 app.listen(port, () => {
   console.log('server is run on port:' + port)
 });

Solution

  • when you are making the HTTP post request from index.html using ajax to verify user authentication details, on successful authentication you are sending a static html file which is simply a text response and will not be rendered as a web page (as you were expecting).

    To solve this problem,

    1. Create a separate route for accessing the mapview.html
        app.get('/map', (req, res) => {
            res.sendFile(__dirname + '/public' + '/mapview.html');
        });
    
    1. In your ajax response just redirect to the map route
        $.ajax({
        url: '/login',
        data: $('#loginForm').serialize(), // Get email and pass from login form 
        type: 'POST',
        success: function (res) {                                      
            console.log(res);
            window.location.href = '/map';  // redirect to map route   
            }   
        });