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

大城市里の小女人 提交于 2019-12-01 12:19:01

When your Javascript sends an Ajax request, the response from that Ajax request is just returned back to your Javascript. That's it. The browser does not show anything. If you want to do something with that response, then it is the responsibility of your Javascript to do something with it (insert it in the page to show it, etc...).

If what you really want is that you want the browser to actually go to the /dashboard URL and then show that page, then your Javascript can just do:

window.location = '/dashboard';

This will tell the browser to fetch the contents of that URL, it will make a request to your server, your server will return the rendered HTML and the browser will display it in the page and show /dashboard as the URL in the browser bar. That should do everything you want.

So, it's totally up to your Javascript. Pick the right tool for the job. Either fetch data for your Javascript with an Ajax call and process the result in your Javascript or instruct the browser to load a new page. One or the other.

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

Yes, that what Ajax requests do. They fetch content from the server and return the data back to your Javascript (and only to your Javascript).

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

Yes, use window.location = '/dashboard'; from your Javascript.

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

Not from an ajax call. Ajax calls never automatically display content. Never. Ajax calls are programmatic requests that return data to your script. That's what they are. But, yes from Javascript you can cause content to be automatically displayed by setting window.location to a new URL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!