如何检索POST查询参数? [英] How to retrieve POST query parameters?

查看:276
本文介绍了如何检索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.email sReq.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.

当我更改为一个获取调用时,它有效,所以..任何想法?

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

推荐答案

p>在 Express 4.0 中再次更改

$ 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()

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天全站免登陆