这是我的简单表单:
<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。查询['email']或sReq。params['邮件'],等等。没有一个有用。它们都返回undefined。
当我更改为Get调用时,它可以工作,所以。任何想法?
如果你想在没有中间件的情况下构建已发布的查询,这可以做到:
app.post("/register/",function(req,res){
var bodyStr = '';
req.on("data",function(chunk){
bodyStr += chunk.toString();
});
req.on("end",function(){
res.send(bodyStr);
});
});
这将把这个发送到浏览器
email=emailval&password1=pass1val&password2=pass2val
使用中间件可能更好,这样你就不必在每条路由中一遍又一遍地写这个。
注:此答案为特快2。请看这里的3号快车。
如果你使用connect/express,你应该使用bodyParser中间件:它在Expressjs指南中有描述。
// example using express.js:
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
var email = req.param('email', null); // second parameter is default
});
以下是仅支持连接的原始版本:
// example using just connect
var connect = require('connect');
var url = require('url');
var qs = require('qs');
var server = connect(
connect.bodyParser(),
connect.router(function(app) {
app.post('/userlogin', function(req, res) {
// the bodyParser puts the parsed request in req.body.
var parsedUrl = qs.parse(url.parse(req.url).query);
var email = parsedUrl.email || req.body.email;;
});
})
);
查询字符串和主体都是使用rails风格的参数处理(qs)来解析的,而不是使用低级的querystring库。为了用qs解析重复的参数,参数需要有括号:name[]=val1&name[]=val2。它还支持嵌套映射。除了解析HTML表单提交外,bodyParser还可以自动解析JSON请求。
编辑:我仔细阅读了Express. js,并修改了我的答案,使其对Express的用户来说更自然。
给定某种形式:
<form action='/somepath' method='post'>
<input type='text' name='name'></input>
</form>
使用快递
app.post('/somepath', function(req, res) {
console.log(JSON.stringify(req.body));
console.log('req.body.name', req.body['name']);
});
输出:
{"name":"x","description":"x"}
req.param.name x
更新
从Express 4.16+版本开始,它们自己的主体解析器实现现在包含在默认的Express包中,因此您不需要下载另一个依赖项。
您可能在代码中添加了如下所示的一行:
app.use(bodyparser.json()); //utilizes the body-parser package
如果您正在使用Express 4.16+,您现在可以将这一行替换为:
app.use(express.json()); //Used to parse JSON bodies
因为express.json()中的代码是基于bodyparser.json()的,所以这不会在应用程序中引入任何破坏性的更改。
如果你的环境中也有以下代码:
app.use(bodyParser.urlencoded({extended: true}));
你可以用:
app.use(express.urlencoded()); //Parse URL-encoded bodies
最后需要注意的是:仍然有一些非常具体的情况下可能仍然需要body-parser,但在大多数情况下,Express的body-parser实现是大多数用例所需要的。
(详见expressjs/bodyparser中的文档)。
后端:
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json()); // add a middleware (so that express can parse request.body's json)
app.post('/api/courses', (request, response) => {
response.json(request.body);
});
前端:
fetch("/api/courses", {
method: 'POST',
body: JSON.stringify({ hi: 'hello' }), // convert Js object to a string
headers: new Headers({ "Content-Type": "application/json" }) // add headers
});
特快4用户注意事项:
如果你试着把app.use(express.bodyParser());进入你的应用程序,你会得到以下错误当你试图启动你的Express服务器:
错误:大多数中间件(如bodyParser)不再与Express捆绑,必须单独安装。请参见https://github.com/senchalabs/connect#middleware。
你必须从npm中单独安装包体解析器,然后使用如下代码(示例取自GitHub页面):
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser());
app.use(function (req, res, next) {
console.log(req.body) // populated!
next();
})