提问者:小点点

如何在Express应用程序中使用JSON POST数据


我正在向服务器发送以下JSON字符串。

(
        {
        id = 1;
        name = foo;
    },
        {
        id = 2;
        name = bar;
    }
)

我在服务器上有这个。

app.post('/', function(request, response) {

    console.log("Got response: " + response.statusCode);

    response.on('data', function(chunk) {
        queryResponse+=chunk;
        console.log('data');
    });

    response.on('end', function(){
        console.log('end');
    });
});

当我发送字符串时,它显示我得到了一个200的响应,但是那些其他两个方法从来没有运行过。这是为什么?


共1个答案

匿名用户

我认为您将response对象的使用与request对象的使用混为一谈。

response对象用于将HTTP响应发送回调用客户端,而您希望访问request的主体。请参阅提供了一些指导的答案。

如果您使用的是有效的JSON,并且用content-type:application/JSON发布它,那么您可以使用BodyParser中间件解析请求主体,并将结果放在路由的request.body中。

对于早期版本的Express(<4)

var express = require('express')
  , app = express.createServer();

app.use(express.bodyParser());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
  response.send(request.body);    // echo the result back
});

app.listen(3000);

按照以下方法进行测试:

$ curl -d '{"MyKey":"My Value"}' -H "Content-Type: application/json" http://127.0.0.1:3000/
{"MyKey":"My Value"}

为Express 4+更新

Body parser在v4之后被拆分到自己的npm包中,需要单独安装npm install body-parser

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

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

Express 4.16+的更新

从版本4.16.0开始,新的express.json()中间件可用。

var express = require('express');

var app = express();

app.use(express.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);