javascript - 有没有办法在node.js中同步读取HTTP请求体的内容?

标签 javascript node.js http post

因此,我将 HTTP POST 请求发送到本地运行的 node.js HTTP 服务器。我希望从 HTTP 正文中提取 JSON 对象,并使用它保存的数据在服务器端执行一些操作。

这是我的客户端应用程序,它发出请求:

var requester = require('request');

requester.post(
        'http://localhost:1337/',
        {body:JSON.stringify({"someElement":"someValue"})}, 
        function(error, response, body){
                if(!error)
                {
                        console.log(body);
                }
                else
                {
                        console.log(error+response+body);
                        console.log(body);
                }
        }
);

这是应该接收该请求的服务器:

http.createServer(function (req, res) {

    var chunk = {};
    req.on('data', function (chunk) {                   
        chunk = JSON.parse(chunk);
    });

    if(chunk.someElement)
    {
            console.log(chunk);
            // do some stuff
    }
    else
    {
        // report error
    }

    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Done with work \n');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

现在的问题是,由于具有回调的 req.on() 函数会异步提取 POST 数据,因此似乎 if(chunk.someElement) 子句是在完成之前进行评估的,因此它总是转到 else 子句,而我根本无法执行任何操作。

  • 有没有更简单的方法来处理这个问题(更简单,我的意思是:不 使用任何其他奇特的库或模块,只是纯 Node )?
  • 有吗 一个同步函数,执行与 req.on() 相同的任务 在我执行之前返回正文的内容 if(chunk.someElement) 检查?

最佳答案

您需要等待并缓冲请求,并在请求的“结束”事件上解析/使用 JSON,因为无法保证所有数据都将作为单个 block 接收:

http.createServer(function (req, res) {

    var buffer = '';
    req.on('data', function (chunk) {
      buffer += chunk;
    }).on('end', function() {
      var result;
      try {
        result = JSON.parse(buffer);
      } catch (ex) {
        res.writeHead(400);
        return res.end('Bad JSON');
      }

      if (result && result.someElement)
      {
        console.log(chunk);
        // do some stuff
      }
      else
      {
        // report error
      }

      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end('Done with work \n');
    }).setEncoding('utf8');
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');

关于javascript - 有没有办法在node.js中同步读取HTTP请求体的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24356481/

相关文章:

javascript - HTML5从其他页面调用变量

javascript - AngularJS中具有多个参数的查询字符串

http - 带有 $http 调用的 AngularJS 工厂在响应准备就绪时我应该关心吗?

python - 将本地文件与 HTTP 服务器位置同步(在 Python 中)

ajax - 决定是使用简单的 HTTP 请求还是 WebSockets

javascript - IOS平台的nativescript应用程序在iPad上完美运行吗?

javascript - 如何在 JavaScript 中使用另一个函数中的变量而不将该变量设置为全局变量?

javascript - 如何设置一个 nodejs 服务器,通过检查 url 为客户端提供正确的文件?

node.js - 查询已完成的级别

对 nodejs 服务器的 C++ POST 请求失败(基于套接字)