您好,我是Node js的新手,我正尝试将数据发送/传递到html,但我似乎无法使其正常工作,并希望有人可以向我指出正确的方向。
服务器代码:
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (request, response) => {
response.sendFile(__dirname + "/views/index.html");
});
app.post('/sendInfo', (req, res) => {
try {
console.log(`firstname: ${req.body.firstname} lastname: ${req.body.lastname}.`);
var firstName = req.body.firstname,
lastName = req.body.lastname;
res.sendFile(__dirname + "/views/info.html", { fistname: firstName, lastname: lastName });
} catch (e) {
console.error("error", e);
}
});
const listener = app.listen(process.env.PORT, () => {
console.log("Your app is listening on port " + listener.address().port);
});
views / info.html代码:
<html>
<head>
<title>My Site title</title>
</head>
<body>
<h1><%= fistname %></h1>
<h1><%= lastname %></h1>
</body>
</html>
答案 0 :(得分:2)
好像您正在使用EJS模板引擎。因此,您的代码中缺少很多东西。
.ejs
而不是.html
res.render()
并传递模板名称和将在模板中使用的JSON数据使用npm init -y
设置一个Node.js项目,然后运行npm install express ejs
,然后创建app.js
文件(下面给出的代码),最后创建views/index.ejs
文件(下面给出的代码)。 views
目录应该与node_modules
目录处于同一级别。
// app.js
const express = require('express');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3006;
const app = express();
app.use(express.static(__dirname + '/build'));
app.use(express.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json({ extended: true }));
app.set('view engine', 'ejs');
app.get('/fn/:first_name/ln/:last_name', (req, res) => {
res.render('index', {
first_name: req.params.first_name,
last_name: req.params.last_name
});
});
app.listen(port, () => {
console.log(`App listening on port ${port}`);
});
// views/index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>First name is <%= first_name %></div>
<div>Last name is <%= last_name %></div>
</body>
</html>
您的package.json
文件必须看起来像这样,请使用start
脚本
{
"name": "node-template",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ejs": "^3.1.5",
"express": "^4.17.1"
}
}
使用npm start
最后,打开浏览器并点击http://localhost:3006/fn/John/ln/Doe
如果一切顺利,您将在浏览器中看到这样的html ...
First name is John
Last name is Doe
输出:
祝你好运。
注意:为简单起见,我使用GET
代替POST
,并使用路径参数代替请求正文。但是模板引擎的工作方式相同。