关于javascript:Express.js如何使用response.render使html呈现在客户端?

Express.js how to make html render on client side with response.render?

我有以下路线的基本表达js应用程序:

1
2
3
router.get('/', function(req, res){
        res.render('login');
    });

它工作正常-登录到我的本地主机上的主页后,login.pug中的html很好地呈现在客户端。但是,当我的应用程序运行时,有时我想呈现另一个pug文件,而客户端已经存在html了:

1
2
3
4
app.get('/dashboard', function(req, res){

    res.render('dashboard', {user: req.query.login});
});

但是,当在'dashboard'路径上发送get请求时,什么也没有发生。据我了解,发生这种情况是因为res.render只是将pug文件解析为HTML并将其作为纯字符串发送到客户端(我可以在浏览器开发人员工具中检查该文件,当我检查AJAX响应时,我看到了完全呈现的HTML)。

现在我的问题是:有没有一种方法可以自动从客户端中的res.render渲染HTML?所以在服务器端我只写res.render('template'),而在客户端页面上重新渲染而不处理响应?

我知道我可以清除整个DOM并将接收到的字符串追加到document.body中,我也可以发出POST表单请求,然后页面将自动重新呈现,但是我想避免两种解决方案(不要问为什么)。

预先感谢您的帮助。


当您的Javascript发送一个Ajax请求时,该Ajax请求的响应只会返回给您的Javascript。而已。浏览器未显示任何内容。如果您想对响应进行某种处理,那么您有责任对Javascript进行处理(将其插入页面中以显示它,等等)。

如果您真正想要的是您希望浏览器实际进入/dashboard URL,然后显示该页面,那么您的Javascript可以做到:

1
window.location = '/dashboard';

这将告诉浏览器获取该URL的内容,它将向您的服务器发出请求,您的服务器将返回呈现的HTML,浏览器将在页面中显示该HTML,并在浏览器栏中显示/dashboard作为URL 。那应该做您想要的一切。

因此,这完全取决于您的Javascript。选择适合该工作的工具。通过Ajax调用获取Javascript数据并在Javascript中处理结果,或指示浏览器加载新页面。非此即彼。

But when get request is send on'dashboard'path, nothing happens. As I understand, this happens because res.render just parses pug file into HTML and sends it to client as plain string (which I can inspect in browser developers tool, when I check AJAX response I see exactly rendered HTML).

是的,Ajax请求可以做到。它们从服务器获取内容,然后将数据返回给Javascript(并且仅返回Javascript)。

is there a way to render HTML from res.render in client automatically?

是的,使用Javascript中的window.location = '/dashboard';

So on server side I just write res.render('template') and on client side page is re-rendered without handling the response?

不是来自ajax调用。 Ajax调用永远不会自动显示内容。决不。 Ajax调用是将数据返回到脚本的程序化请求。那就是他们。但是,是的,通过Java,您可以通过将window.location设置为新的URL来自动显示内容。