表达js表单数据 [英] Express js form data

查看:30
本文介绍了表达js表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我推荐的(最新的)方式来获取快速发布的表单数据.

Can someone please tell me the recommended (up to date) way to get POSTed form data in express.

很多教程/帖子等都在谈论 bodyParser,但这不再与 Express 捆绑在一起,其他博客等建议直接使用 urlencoded,但现在也不可用.

So many tutorials/ posts etc talk about bodyParser but this is no longer bundled with Express and other blogs etc recommend using urlencoded directly, but now this is not available either.

我正在努力寻找有关这些框架或技术的准确信息.

Trying to find accurate information on these frameworks or technologies is doing my head in.

顺便说一句,我感兴趣的是非常简单的小型数据

BTW what I am intrerested in is very simple and small form data

推荐答案

你应该通过 npm-install 安装 body-parser.现在它作为一个单独的中间件出现.

You should install body-parser through npm-install. Now it comes as a separate middleware.

在你的 app.js 中添加以下行

After that add following line in your app.js

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
// in latest body-parser use like below.
app.use(bodyParser.urlencoded({ extended: true }));

它将post 请求解析为object.您将在 req.body 中获取变量.

It parses the post request as an object. You will get your variables in req.body.

在您的 post 请求处理程序中.

In your post request handler.

app.post('/post',function(request,response){
   console.log(request.body) //you will get your data in this as object.
})

编辑 1

上面的答案是针对专门提出的问题,OP 正在寻找 bodyParser(已弃用),它不再是 express 的一部分.

Edit 1

The answer above was for the question specifically asked, the OP was looking for the bodyParser(deprecated) which was not part of express anymore.

由于问题的标题很笼统,而且答案并不包括form-data的所有方面,我将@StLia的答案作为编辑.

Since the title of the question is very generic and the answer doesn't include all aspects of form-data, I will put @StLia's answer as an edit.

Body-Parser 自述文件

由于其复杂且通常较大的性质,这不处理多部分实体.对于多部分主体,您可能对以下模块感兴趣:

This does not handle multipart bodies, due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆