from.. 2011-04-19 00:38 采纳率: 100%
浏览 135
已采纳

如何检索 POST 查询参数?

Here is my simple form:

<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>

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

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

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?

转载于:https://stackoverflow.com/questions/5710358/how-to-retrieve-post-query-parameters

  • 写回答

18条回答 默认 最新

  • 七度&光 2012-08-17 15:30
    关注

    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.

    This was different starting Express 4.0 to 4.15:

    $ npm install --save body-parser
    

    and then:

    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
    })); 
    

    The rest is like in 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
    

    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;
        // ...
    });
    

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

    app.use(express.bodyParser());
    

    ...is equivalent to:

    app.use(express.json());
    app.use(express.urlencoded());
    app.use(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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(17条)

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算