简体   繁体   English

在 Express Node JS 中,如何处理用户同时请求 HTML 页面和发送请求参数的请求?

[英]In express Node JS , how do I handle a request in which the user requests both a HTML page and a sends a request parameter?

I am creating a web app where a user can type in /poll/:id in order to retrieve a poll with the given id from my database.我正在创建一个 web 应用程序,用户可以在其中输入 /poll/:id 以便从我的数据库中检索具有给定 ID 的投票。 Presumably, in order to do this, my Node JS express server would first need to send over the HTML I want the poll to be displayed on, the JavaScript that handles the frontend and then JSON data representing the poll.据推测,为了做到这一点,我的 Node JS Express 服务器首先需要发送我希望显示投票的 HTML,处理前端的 JavaScript,然后是代表投票的 JSON 数据。

I am running into a roadblock because I have no idea how to handle such a request.我遇到了障碍,因为我不知道如何处理这样的请求。 As a jumping off point, I tried to make my server simply send over the html page in question upon receiving the request (and hence not using express's static server).作为一个起点,我试图让我的服务器在收到请求时简单地发送有问题的 html 页面(因此不使用 express 的 static 服务器)。 The code is as follows:代码如下:

app.get('/poll/:id', function(req, res, next){
    res.sendFile('poll.html');
    
});

However, the page on the user's end does not handle any of the CSS, hence the page is not styled at all upon being sent to the user, nor is the frontend JS supported.但是,用户端的页面不处理任何 CSS,因此该页面在发送给用户时根本没有样式,也不支持前端 JS。 What exactly do I have to do in order to ensure all of that is functional in the frontend?为了确保所有这些在前端都能正常运行,我到底需要做什么? Is there an easier approach to this that I am not realizing?有没有我没有意识到的更简单的方法?

If you want to generate the HTML on the server-side, use a templating engine, ejs for example.如果要在服务器端生成 HTML,请使用模板引擎,例如 ejs。 There u would be able to retrieve the data from the database and easily render the page according to that data.您将能够从数据库中检索数据并根据该数据轻松呈现页面。 On the other hand, if you want to retrieve the data using javascript then just serve the HTML files statically, and then create another route which would only respond with the JSON object retrieved from the database, (which the frontend would request), and then the frontend-javascript would render the application另一方面,如果您想使用 javascript 检索数据,那么只需静态提供 HTML 文件,然后创建另一条路由,该路由只会响应从数据库中检索到的 JSON object(前端会请求),然后frontend-javascript 将呈现应用程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM