如何访问POST表单字段 [英] How to access POST form fields

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

问题描述

这是我的简单表格:

<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代码:

Here is my Express.js/Node.js code:

app.post('/userlogin', function(sReq, sRes){    
    var email = sReq.query.email.;   
}

我尝试了sReq.query.emailsReq.query['email']sReq.params['email']等.它们都不起作用.它们都返回undefined.

I tried sReq.query.email or sReq.query['email'] or sReq.params['email'], etc. None of them work. They all return undefined.

当我更改为Get呼叫时,它可以工作,所以..有什么想法吗?

When I change to a Get call, it works, so .. any idea?

推荐答案

事物具有更改,再次从 Express 4.16.0 开始,您现在可以像在 Express 3.0 中一样使用express.json()express.urlencoded().

Things have changed once again starting Express 4.16.0, you can now use express.json() and express.urlencoded() just like in Express 3.0.

Express 4.0到4.15 开始,这是不同:

This was different starting Express 4.0 to 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 :

首先,您需要添加一些中间件来解析正文的发布数据.

Firstly you need to add some middleware to parse the post data of the body.

添加以下两行代码之一或全部:

Add one or both of the following lines of code:

app.use(express.json());       // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies

然后,在您的处理程序中,使用 req.body 对象:

Then, in your handler, use the req.body object:

// 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() .


Note that the use of express.bodyParser() is not recommended.

app.use(express.bodyParser());

...等效于:

app.use(express.json());
app.use(express.urlencoded());
app.use(express.multipart());

express.multipart()存在安全问题,因此最好显式添加对所需特定编码类型的支持.如果您确实需要分段编码(例如,以支持上传文件),则应该

Security concerns exist with express.multipart(), and so it is better to explicitly add support for the specific encoding type(s) you require. If you do need multipart encoding (to support uploading files for example) then you should read this.

这篇关于如何访问POST表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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