提问者:小点点

节点js将post数据传递/发送到html


你好,我是node js的新手,我正在尝试发送/传递post数据到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>

共1个答案

匿名用户

看起来您正在使用EJS模板引擎。因此,您的代码中缺少了许多东西。

  1. 您需要告诉express您正在模板引擎中使用EJS
  2. 视图的扩展名必须为.ejs,而不是.html
  3. 您应该使用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,并使用了路径参数而不是请求体。但是模板引擎的工作方式是相同的。

相关问题