简体   繁体   English

expressjs无需任何引擎即可渲染html文件

[英]expressjs render html file without any engine

I am new to nodejs and expressjs I am trying to develop a simple login page which has a username field and a password inside a form. 我是nodejs和expressjs的新手,我试图开发一个简单的登录页面,该页面在表单内具有用户名字段和密码。 on submit of the form i will redirect the user to a home page where i will display the message welcome user- userName. 在提交表格时,我会将用户重定向到主页,在其中显示消息Welcome user-userName。 I want both the login and home pages to be simple html files. 我希望登录页面和主页都是简单的html文件。 The form in login page has action set to home.html so when the user submits the form i can get the user name and password using res.body.userName and res.body.password. 登录页面中的表单将操作设置为home.html,因此,当用户提交表单时,我可以使用res.body.userName和res.body.password获取用户名和密码。 My question is how to use express to render html file. 我的问题是如何使用express呈现html文件。 I do know that i can use res.sendfile function to send a html file but sendfile function does not support sharing variables to the html file. 我知道我可以使用res.sendfile函数发送html文件,但sendfile函数不支持将共享变量共享到html文件。 I have posted below my code in app.js 我已经在app.js中的代码下方发布了

var http = require("http");
var express = require("express");
var app = express();
app.use(express.bodyParser());
app.all("/",function(req,res,next){
    res.render("login.html");
});
app.all("/home.html",function(req,res,next){
    res.render("home.html",{"userName":req.body.userName});
})
http.createServer(app).listen(3000,function(){
    console.log("Listening at port 3000");
})

You don't need a rendering engine to serve up static assets like html files. 您不需要渲染引擎即可提供html文件等静态资产。 You should rethink what is being served up on different request but for what you want you have to place your static assets in a directory and tell express where they are like so 您应该重新考虑在不同请求下要处理的内容,但是对于您想要的内容,必须将静态资产放置在目录中并告诉express它们的位置

app.use(express.static('public'));

Assuming your server file is on the root, and you have an public folder on the root as well, put your html files in the folder. 假设你的服务器文件的根,和你有一个public的根文件夹为好,把你的HTML文件的文件夹中。 By default, express will look for an index.html file in the foot of that public folder and serve it on a GET request to / . 默认情况下,express将在该公用文件夹的末尾查找index.html文件,并将其提供给/GET请求。 You are overriding that by serving your login page. 您正在通过提供登录页面来覆盖它。 That's fine. 没关系。 You have to use res.sendfile('/path/to/file') instead of res.render() 您必须使用res.sendfile('/path/to/file')而不是res.render()

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

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