【问题标题】:Node.js: receiving input from HTML select without document.getElementByIdNode.js:从没有 document.getElementById 的 HTML 选择接收输入
【发布时间】:2026-02-03 10:15:02
【问题描述】:

我正在开发一个 node.js 项目,该项目涉及选择某人的姓名并重定向用户以获取更多信息。但是,当我尝试 console.log 结果时,只是为了检查我是否可以检索这些值,我什么也没得到。 下面是我的代码示例:

function displayDetailed(data, req) {
  names = data[0];
  var input = '<select name = "dropDown" onChange = "testing(this)">;
  for (var i = 0; i < names.length; i++) {
    input += '<option value= "' + i + '" name = "employee" > ' + names[i] + ' </option>';
  }
  input += '</select><br>';
  var myData = {
    test: req.body
  }
  console.log(myData);
  return '<!DOCTYPE html><head></head><body>' + input + '</body></html>';
}

function testing(name) {
  console.log('Testing!  ' + name);
}

显然,我现在只想将员工的姓名打印到控制台上。但是,控制台上没有弹出任何内容,无论是名称还是任何错误。

我还尝试了在其他 * 帖子(ExampleExample1)上看到的多种解决方案。这就是我想到 test var 的地方。出于某种原因,当我尝试调用它时请求的正文不存在,只是返回undefined

我也不能调用document.getElementById,因为 node.js 没有 DOM。链接的解决方案实现了这个函数,我不能调用它,因为 node.js 不允许我调用用户正在处理的 html 文档。

此函数将返回一个 HTML 字符串到 express app.get 中的 res.send 调用。

【问题讨论】:

标签: javascript html node.js express


【解决方案1】:

简答:

我怀疑您的问题是您没有使用正文解析器中间件来解析请求正文。


加长版:

假设您在项目根目录中名为 html 的目录中有一个名为 index.html 的 HTML 文件:

<!doctype html>

<meta charset=utf-8>
<title>Test</title>

<body>
    <form action="/" method="post">
        <select name="values">
            <option value="value1">Value 1</option>
            <option value="value2">Value 2</option>
        </select>
        <input type="submit">
    </form>
</body>

您可以使用 built-in static middleware 将该文件提供给客户端(或构建 HTML 字符串并将其作为响应发送给客户端,或者使用 a template engine 让您的生活更轻松)然后使用正文解析器中间件(像this one) 在提交表单时解析请求体:

const http = require('http');
const path = require('path');

const bodyparser = require('body-parser'); // npm i body-parser
const express = require('express');

const app = express();

const PORT = process.env.PORT || 8080;
const server = http.createServer(app);
server.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

app.use(express.static(path.join(__dirname, './html')));
app.use(bodyparser.urlencoded({extended: true}));

app.post('/', (req, res) => {
  res.setHeader('content-type', 'text/plain');
  res.end(`You have selected: ${req.body.values}`);
});

【讨论】: