javascript - Node.js express:试图从 HTML 表单中获取文本,req.body 为空
问题描述
我正在尝试构建一个基本的文本到语音表单,但我无法从表单中获取文本。我正在尝试使用快速服务器从 HTML 表单中获取文本,并且 req.body 每次都显示为空。我尝试使用 body-parser 并更改表单上的 enctype,但似乎没有任何效果。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>index.html</title>
</head>
<body>
<h1>Speech!!</h1>
<main>
<form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
<div id="text-container">
<label for="text-box">Text to Speech!</label>
<input type="text" id="text-box" title="text" placeholder="Type what you want to say here!"/>
</div>
<div class="button-container">
<button type="submit" id="submit-button">Speak!</button>
</div>
<div class="button-container">
<button type="reset" id="clear-form">Clear Text</button>
</div>
</form>
</main>
</body>
</html>
应用程序.js
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const configRoutes = require("./routes");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
configRoutes(app);
app.listen(3000, () => {
console.log("Speech Server");
});
index.js
const express = require("express");
const speakRoutes = require("./speak");
const constructorMethod = (app) => {
app.use("/speak",speakRoutes);
app.use("*", (req,res) => {
res.sendFile("index.html", { root: "./public" });
});
};
module.exports = constructorMethod;
说话.js
const express = require("express");
const router = express.Router();
router.post("/", async (req,res) => {
console.log("POST");
console.log(req.body);
res.sendFile("index.html", { root: "./public" });
});
module.exports = router;
我将不胜感激一些帮助!谢谢!
解决方案
您的输入没有名称,请为您的输入命名,以便您知道要在表单中查找的属性:
<input type="text" id="text-box" name="whatever" ... />
编辑:仅限客户端的示例。一个字段有一个名称。
$('form').on('submit', function(e) {
e.preventDefault();
console.log($(e.currentTarget).serialize());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Speech!!</h1>
<main>
<form action="/speak" method="POST" id="speak-form" enctype="multipart/form-data">
<div id="text-container">
<label for="text-box">Text to Speech!</label>
<input type="text" id="text-box" title="text" placeholder="Type what you want to say here!" name="whatever" />
<input type="text" id="text-box" title="text" placeholder="I have no name so I won't be sent!" />
</div>
<div class="button-container">
<button type="submit" id="submit-button">Speak!</button>
</div>
<div class="button-container">
<button type="reset" id="clear-form">Clear Text</button>
</div>
</form>
</main>
推荐阅读
- javascript - classList 的 JavaScript 问题
- python - 有谁知道如何更改函数,以便仅将生成的列表输出到 csv,而 df 中的每一行都不会被范围内的数字分割?
- jboss - 当我有 1000 多个规则时,如何优化我的 Kiebase 构建时间?
- python - 尝试使用 Scrapy 抓取时出现 555 HTTP 协议
- azure-devops - Task.json azure devops 扩展隐藏输入
- python - python中的异步错误
- hugo - 在 hugo 中替换 .Page.UniqueID 以解决弃用警告
- reactjs - 在表上使用 redux 是否值得?
- python - Python:相互依赖的类
- kdb - 在 KDB 中加载两个分区表时列值发生变化 (q)