这是我的简单表格:
<form id="loginformA" action="userlogin" method="post">
<div>
<label for="email">Email: </label>
<input type="text" id="email" name="email"></input>
</div>
<input type="submit" value="Submit"></input>
</form>
这是我的Express.js/Node.js 代码:
app.post('/userlogin', function(sReq, sRes){
var email = sReq.query.email.;
}
我试过 sReq.query.email
或 sReq.query['email']
或 sReq.params['email']
,等等。它们都不起作用。它们都返回 undefined
。
当我更改为 Get 调用时,它可以工作,所以.. 有什么想法吗?
最佳答案
事情有changed再次启动 Express 4.16.0,您现在可以像在 中一样使用 express.json()
和 express.urlencoded()
Express 3.0。
这是 different开始 Express 4.0 到 4.15:
$ npm install --save body-parser
然后:
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
其余的就像 Express 3.0 中的:
首先你需要添加一些中间件来解析body的post数据。
添加以下一行或两行代码:
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
然后,在您的处理程序中,使用 req.body
对象:
// assuming POST: name=foo&color=red <-- URL encoding
//
// or POST: {"name":"foo","color":"red"} <-- JSON encoding
app.post('/test-page', function(req, res) {
var name = req.body.name,
color = req.body.color;
// ...
});
注意使用express.bodyParser()
不推荐。
app.use(express.bodyParser());
...等价于:
app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());
express.multipart()
存在安全问题,因此最好明确添加对您需要的特定编码类型的支持。如果您确实需要多部分编码(例如支持上传文件),那么您应该 read this .
关于javascript - 如何在 Express 中访问 POST 表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5710358/