不使用BodyParser在Express中解析JSON

不使用BodyParser在Express中解析JSON,json,node.js,express,request,Json,Node.js,Express,Request,我正在尝试编写一个简单的express服务器,它接收传入的JSON(POST),解析JSON并分配给请求主体。问题是我不能使用bodyparser。下面是我的服务器,其中一个简单的中间件功能被传递给app.use 问题:每当我使用superagent(允许您通过终端发送JSON的npm包)向我的服务器发送虚拟POST请求时,我的服务器就会超时。我使用req.on('data')以类似的方式编写了一个HTTP服务器……所以我被难住了。有什么建议吗 const express = require('

我正在尝试编写一个简单的express服务器,它接收传入的JSON(POST),解析JSON并分配给请求主体。问题是我不能使用bodyparser。下面是我的服务器,其中一个简单的中间件功能被传递给app.use

问题:每当我使用superagent(允许您通过终端发送JSON的npm包)向我的服务器发送虚拟POST请求时,我的服务器就会超时。我使用req.on('data')以类似的方式编写了一个HTTP服务器……所以我被难住了。有什么建议吗

const express = require('express');
const app = express();

function jsonParser(req, res, next) {
  res.writeHead(200, {'Content-Type:':'application/json'});
  req.on('data', (data, err) => {
    if (err) res.status(404).send({error: "invalid json"});
    req.body = JSON.parse(data);
  });
  next();
};

app.use(jsonParser);
app.post('/', (req, res) => {
  console.log('post request logging message...');
});

app.listen(3000, () => console.log('Server running on port 3000'));

我认为问题在于把罗博迪放进快递

就这样,

app.use(function(req, res, next){
   var data = "";
   req.on('data', function(chunk){ data += chunk})
   req.on('end', function(){
       req.rawBody = data;
       req.jsonBody = JSON.parse(data);
       next();
   })
})
您需要捕获将字符串解析为json时的错误,并需要判断
Req
内容类型


祝你好运。

另一种方法是将所有块收集到一个数组中并解析连接的块

app.use("/", (req, res, next)=>{

    const body = [];
    req.on("data", (chunk) => {
        console.log(chunk);
        body.push(chunk);
    });
    req.on("end", () => {
        const parsedBody = Buffer.concat(body).toString();
        const message = parsedBody.split('=')[1];
        console.log(parsedBody);
        console.log(message);
    });
    console.log(body);
});

在Express v4.16.0及以后的版本中:

app.use(express.urlencoded({ extended: true }))

出于某种奇怪的原因,JSON.parse抛出了一个异常,因为数据最后是空的,但如果我捕捉到它,req.rawBody稍后会有JSON文本。