【问题标题】:View is not change after render .pug file from express从 express 渲染 .pug 文件后视图没有变化
【发布时间】:2017-08-09 00:06:54
【问题描述】:

我有一些问题,在渲染 pug 文件后,获得服务器响应后 html 视图没有改变。

代码如下

app.set('view engine', 'pug');
 app.set("views", require('path').join(__dirname, "views"));

app.post('/login', function(req, res, next) {
console.log(req.body);
checkExistanceOfuser(req.body.username, req.body.password, function(err, flag, data) {
    console.log(err);
    if (err) {
        res.send({
            err: 'SOME_DATABASE_ERROR'
        })
    } else {
        if (flag) {

            req.session.user = data;

            /*res.send({
                success: true,
                message: 'Login Success'
            })*/

            res.render('welcome', { name: data.name });
        } else {
            /*res.send({
                success: false,
                message: 'Invalid Credentials'
            });*/
            res.render('login', { error: 'Invalid Credentials' });
        }
    }
})

但我从浏览器检查网络部分。API 响应(预览)很好。

【问题讨论】:

  • 是页面不渲染的问题吗?哪个页面?

标签: javascript express pug


【解决方案1】:

当您调用/login route 时,这是一个post call,可能您正在使用ajax post call 来执行此操作。 现在,当您调用 /login 路由时,它会渲染 pug 文件 但它实际上并没有影响浏览器 DOM。所以你需要做的是这个

像这样创建一条新路线

  app.get('/login-success', function(req, res, next) {
        if (req.session && req.session.user) {
            res.render('welcome', { name: req.session.user.name });
        } else {
        res.redirect('/');
        }
  });

并像这样修改登录功能

   app.post('/login', function(req, res, next) {
      console.log(req.body);
      checkExistanceOfuser(req.body.username, req.body.password, function(err, flag, data) {
      console.log(err);
      if (err) {
         res.send({
            err: 'SOME_DATABASE_ERROR'
         })
      } else {
            if (flag) {

                req.session.user = data;

                res.send({
                    success: true,
                    message: 'Login Success'
                });
             } else {
                res.send({
                success: false,
                message: 'Invalid Credentials'
                });
             }
          }
      })
  });

在 ajax 调用中使用这个

function login(){
  $.post("http://localhost:8000/login",
  {
    username:document.getElementById("name").value,
    password:document.getElementById("password").value,
  },
  function(data, status){
     if(data.success){
      window.location = "http://localhost:8000/login-success"
     }
  });
  }

【讨论】:

  • 感谢您的回答
【解决方案2】:

您正在渲染views/login,但您已经指定视图文件夹为views。只需渲染login

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-01
    • 2017-06-16
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多