Reputation: 1
I'm trying to build a basic text to speech form, but I cannot grab the text from the form. I'm trying to get text from an HTML form using an express server and req.body turns up empty every time. I've tried using body-parser and changing the enctype on the form, nothing seems to work.
<!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>
app.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;
speak.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;
I would greatly appreciate some help! Thank you!
Upvotes: 0
Views: 154
Reputation: 1
I fixed my own issue! It worked by changing post
to get
in the route and the html form method, and req.body
to req.query
Upvotes: 0
Reputation: 3126
Your input has no name, give your input a name so you know what property to look for in the form:
<input type="text" id="text-box" name="whatever" ... />
EDIT: A client-only example. One field has a name.
$('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>
Upvotes: 1