簡體   English   中英

有沒有一種方法可以同步讀取node.js中HTTP請求正文的內容?

[英]Is there a way to synchronously read the contents of HTTP request body in node.js?

因此,我正在向本地運行的node.js HTTP服務器發送HTTP POST請求。 我希望從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)子句在執行之前if(chunk.someElement)被求值,因此它總是轉到else子句和我什么也做不了。

  • 有沒有更簡單的方法來處理此問題(更簡單地說,我的意思是:不使用任何其他奇特的庫或模塊,僅使用純節點)?
  • 是否有一個同步函數執行與req.on()相同的任務,並在執行if(chunk.someElement)檢查之前返回主體的內容?

您需要等待並緩沖請求,然后在請求的“結束”事件上解析/使用JSON,因為無法保證所有數據都將作為單個塊接收:

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/');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM