NodeJS 接收表单数据
最为常见的数据提交就是通过网页表单提交数据到服务器端,如下所示:
<form action="/upload" method="post"> <label for="username">用户名:</label> <input type="text" name="username" /> <input type="submit" name="submit" value="Submit" /> </form>
默认的表单提交,请求头中的 Content-Type
字段值为 application/x-www-form-urlencoded
,如下所示:
Content-Type: application/x-www-form-urlencoded
由于它的报文体内容跟查询字符串相同:
foo=bar&baz=val
因此解析它十分容易:
var hasBody = function (req) { return 'transfer-encoding' in req.headers || 'content-length' in req.headers; };
function handle(req, res) { if (hasBody(req)) { var buffers = []; req.on('data', function (chunk) { buffers.push(chunk); }); req.on('end', function () { req.rawBody = Buffer.concat(buffers).toString(); if (req.headers['content-type'] === 'application/x-www-form-urlencoded') { req.body = querystring.parse(req.rawBody); } }); } }
后续业务中直接访问 req.body
就可以得到表单中提交的数据。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论