繁体   English   中英

html 文件在登录后没有出现任何错误

[英]html file does not appear after logging without any error

我是服务器端编程的新手。 我正在尝试在身份验证后提供 HTML 文件(mapview.html),但没有出现任何错误 认证过程没有问题。 我希望当我单击登录按钮时,代码会检查 req 数据并在验证后弹出 mapview.html但没有任何反应。 res.sendFile() 导致 jquery 部分,console.log(res),让我在 chrome 的控制台行中获取所有 html 代码。


文件目录:

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

索引.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)                       
           }   
      })

  })

用户.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)
 });

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 )。

为了解决这个问题,

  1. 为访问mapview创建单独的路由。html
    app.get('/map', (req, res) => {
        res.sendFile(__dirname + '/public' + '/mapview.html');
    });
  1. 在您的 ajax 响应中,只需重定向到 map 路线
    $.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   
        }   
    });

我更新了代码,它看起来像下面的代码。 正如我在过去的评论中提到的,我需要在 refirect through.href = '/map' 之前进行身份验证,我不知道如何将令牌附加到 .href='/map 我们通常发送令牌为 header 和 ajax 像这样: headers:{"Authorization": localStorage.getItem('token')}

如果我将它添加到.href,像这样的 window.location.href = '/map + "?token=MY_TOKEN",我怎样才能在 auth 方法中得到它?


用户.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'));     
 });

索引.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';     
               }                       
            }) 
        })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM