这是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="/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>
这是在服务器上运行的node.js函数:
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.post('/myaction', function (req, res) {
var myString="name";
console.log(req.body.myString);
res.end("thanks\n");
})
输出是
undefined
但是当我输出console.log(request.body)时,会显示输入值。我在这做错了什么?是不是可以将字符串附加到request.body。请帮忙
发布于 2018-08-24 16:11:10
你在这里做的是试图在命名的req.body中找到一个myString
字段。如果要使用字符串选择字段,可以将对象视为使用字符串索引的数组。所以在你的情况下它将是:
app.post('/myaction', function (req, res) {
var myString="name";
console.log(req.body[myString]);// notice how we get the value of req.body here
res.end("thanks\n");
});
这将使值成为变量myString
并使用它为对象编制索引,就像你写的那样:req.body['name']
https://stackoverflow.com/questions/-100002398
复制相似问题