我想将所有3个HTML表单字段(名称,电子邮件,消息)写入文本文件。当我尝试调用req.body.message或req.body.email它不起作用时,我似乎只能让名字起作用。我错过了什么?
server.js
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var fs = require('fs');
app.use(bodyParser.urlencoded({ extended: true }));
//app.use(express.bodyParser());
app.post('/myaction', function(req, res) {
res.send('You sent the name "' + req.body.name + '".');
fs.writeFile('file.txt', req.body.name, function(err) {
if (!err) {
console.log('Wrote data to file.txt');
} else {
throw err;
}
});
});
app.listen(8080, function() {
console.log('Server running at http://127.0.0.1:8080/');
});
HTML表单
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CSS3 Contact Form</title>
</head>
<body>
<div id="contact">
<h1>Send an email</h1>
<form action="http://127.0.0.1:8080/myaction" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<label for="email">Email:</label>
<input type="email" id="email" placeholder="Enter your email address" />
<label for="message">Message:</label>
<textarea id="message" placeholder="What's on your mind?"></textarea>
<input type="submit" value="Send message" />
</fieldset>
</form>
</div>
</body>
</html>
答案 0 :(得分:2)
你应该添加&#34;名称&#34;属性为HTML
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email address" />
<label for="message">Message:</label>
<textarea id="message" name="message" placeholder="What's on your mind?"></textarea>