0

我是服务器端编程的新手。我正在尝试在身份验证后提供 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)
 });
4

2 回答 2

0

当您使用 ajax 从 index.html 发出 HTTP 发布请求以验证用户身份验证详细信息时,在成功身份验证时,您将发送一个静态 html 文件,该文件只是一个文本响应,不会呈现为网页(如您所料)。

为了解决这个问题,

  1. 为访问 mapview.html 创建单独的路由
    app.get('/map', (req, res) => {
        res.sendFile(__dirname + '/public' + '/mapview.html');
    });
  1. 在您的 ajax 响应中,只需重定向到地图路线
    $.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   
        }   
    });
于 2020-06-19T07:07:13.713 回答
0

我更新了代码,它看起来像下面的代码。正如我在过去的评论中提到的,我需要在通过 .href = '/map' 重新触发之前进行身份验证,并且我不知道如何将令牌附加到 .href='/map。我们通常将令牌作为带有 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';     
               }                       
            }) 
        })
于 2020-06-20T03:02:49.273 回答