0

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)
 });

2 Answers2

0

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   
        }   
    });
arnabxm
  • 149
  • 7
  • the problem is app.get('/map', (req, res) is available easily and it should have authentication so I changed it to router.get('/map', auth, (req, res). but I need somehow attach token to window.location.heref='/map' . token already send back to localstorage and i can easily get it but i do not know how attach it to .href='/map' – ehsanpaknahad Jun 20 '20 at 02:49
  • It is not possible to attach auth token in window.location.href. But you can make use of sessions to achieve this. – arnabxm Jun 20 '20 at 06:12
0

I updated the codes and it looks like following code . As I mention in the past comment , I need to authenticate before refirect through .href = '/map' and I do not know how to attach token to .href='/map. we usually send token as header with ajax like this: headers:{"Authorization": localStorage.getItem('token')}

in case I add it to .href ,something like this window.location.href = '/map + "?token=MY_TOKEN" , how can i get it in auth method?


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()        
     res.send({user, token})        

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

 router.get('/map', auth, (req, res) => {
   const publicDir = path.join(__dirname, '../public') 
   res.sendFile(path.join(publicDir + '/mapview.html'));     
 });

index.html

         $('div[name="logIn"]').click( () => {                  
            $.ajax({
               url: '/login',
               data: $('#loginForm').serialize(),  
               type: 'POST',
               success: function (res) { 
                  localStorage.setItem('token', res.token);    
                  window.location.href = '/map';     
               }                       
            }) 
        })
  • the problem solved.. to whom might encounter with this problem i could get the token through req._parsedOriginalUrl.query .. and that worked ... – ehsanpaknahad Jun 20 '20 at 06:03