Express未显示从POST请求收到任何参数

时间:2014-07-25 06:36:50

标签: node.js express

在节点中,我使用express.router()来接收curl请求。我只是想做一个'#34; hello world"并记录我收到的任何内容

我的卷曲请求:

curl -F "hello_world=foobar" http://examplesite.com/my_endpoint

Node如何处理它:

var express = require('express');
var router = express.Router();
router.route('/my_endpoint')
  .post(function(req, res){
    var data = req.body;
    console.log(data); // This comes back blank... shouldn't it have "hello_world=foobar"?
  });

3 个答案:

答案 0 :(得分:2)

req.body在Express-App中自然不存在。为此,您需要表达身体解析器中间件。安装时使用:

npm install body-parser --save

之后,您可以通过以下方式轻松将其添加到您的应用中:

var express = require('express');
var bodyParser = require('body-parser'); 

var app = express(); // Instantiate an express app
app .use(bodyParser.urlencoded({ extended: false })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json

var router = app.Router();
router.route('/my_endpoint')
  .post(function(req, res){
    var data = req.body;
    console.log(data); // This comes back blank... shouldn't it have "hello_world=foobar"?
  });

修改 我还看到你如何实例化你的快递应用程序有一点错误。你不要在表达本身上使用路由器,但是在你之前通过调用express实例化的应用程序。我在上面的例子中对它进行了编辑。

答案 1 :(得分:1)

我会做的有点不同,

var express = require('express');
var app = express(); 
var http = require('http').Server(app);


app.post('/myendpoint', function (req, res) {
    var body = "";
    req.on('data', function (data) {
        body += data;
    });
    req.on('end', function () {
        console.log(body); //will print hello_world=Foobar
    });

答案 2 :(得分:0)

在2020年1月遇到同样的挑战:

使用Express 4.16 +。

您不再需要安装body-parser

相反,只需将router.use(express.json());添加到路由文件中,如下所示:

// in ./routes/routingFile.js:

const express = require('express');
const router = express.Router();
router.use(express.json());         // to support JSON-encoded bodies

现在您的请求将包含正文。