【问题标题】:How do I get the post request with express js?如何使用 express js 获取 post 请求?
【发布时间】:2014-01-27 01:04:40
【问题描述】:

我正在尝试在我编写的一个小服务中获取发布变量,但似乎无法从我的 app.post 方法中的请求变量中获取它。我相信这是我处理请求的某种方式。我必须采取其他步骤来处理请求吗?我也尝试过使用 express.bodyParser() 但我得到一个错误,说这已被弃用。以下是我的小 node.js 文件:

        var express = require('express');
        var app = express();
        app.use(express.json());
        // posting method : curl -X POST http://localhost:8080/post-page -d name=ArrowKneeous
        // to look at the req I found it better to start using: 
        // nohup node testPost.js > output.log &
        app.post('/post-page',function(req,res){
        var name= req.body.name;
        //undefined
        console.log('name is :' + name);
        //object
         console.log('req is: '+req);
        //object
        console.log('req.body is: ' +req.body);
        //undefined
        console.log('req.body.name is: '+req.body.name);
        //undefined
         console.log('req.params[0]: '+req.params[0]);
         //undefined
         console.log('req.query.name is: '+req.query.name);
         //empty brackets
         console.dir(req.body);
         //huge
         console.dir(req);
         //got stuff is replied to the curl command
         res.send('got stuff');
       });
    app.listen(8080);

【问题讨论】:

    标签: node.js http post express


    【解决方案1】:

    你有

    app.use(express.json());

    处理 JSON 帖子,但正在发布标准 URL 编码的表单数据。

    -d name=ArrowKneeous

    您需要发布 JSON

    -d '{"name": "ArrowKneeous"}' -H "Content-Type: application/json"
    

    或者您需要告诉 express 也接受 URL 编码的 POST 数据。

    app.use(express.urlencoded());
    

    编辑

    这适用于 Express 3.x。它应该与4.x 几乎相同,但您需要加载body-parser 模块:

    var bodyParser = require('body-parser');
    
    app.use(bodyParser.json());
    // OR
    app.use(bodyParser.urlencoded());
    

    【讨论】:

    • 很好的答案,@loganfsmyth。大多数人只会说app.use(express.bodyParser()),但我更喜欢直接使用jsonurlencoded,因为multipart(目前包含在bodyParser 中)很快就会被弃用。
    • 我在尝试使用建议的解决方案时遇到错误:错误:大多数中间件(如 json)不再与 Express 捆绑,必须单独安装
    • @Igal 已更新。请记住,Express 有一个新的主要版本 (4.x),因此任何超过一个月左右的答案都可能不准确。
    猜你喜欢
    • 2019-11-04
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-12
    相关资源
    最近更新 更多