本文介绍了从express快速渲染.pug文件后,视图不会更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some problem that the html view is not change after render the pug file,after getting the server response.

代码如下

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响应(预览)很好。

But i check in network section from browser.The API response (preview) is fine.

推荐答案

当你打电话给 / login 路线这是一个后调用,可能你正在使用ajax post call这样做。
现在,当您调用 / login 路由时,它会呈现 pug 文件
但是实际上并没有影响浏览器DOM。所以你需要做的就是这个

when you are calling /login route it's a post call and probably you are using ajax post call for doing so.Now when you are calling the /login route its rendering the pug filebut its not actually effecting the browser DOM. So what you need to do is this

创建一个像这样的新路线

create a new route like this

  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电话中使用此

in ajax call use this

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

这篇关于从express快速渲染.pug文件后,视图不会更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 02:13