簡體   English   中英

節點JS HTTP請求不使用http請求執行任何操作

[英]node JS HTTP request does nothing using http request

我正在嘗試使用本機節點js http請求發送http post請求。 我正在使用以下代碼,但沒有任何反應:

    var http = require('http');

    var options = {
      hostname: '192.168.1.134',
      port: '8082',
      path: '/api',
      method: 'POST',
      headers: {'content-type': 'application/json',
      'cache-control': 'no-cache'}
    };

    callback = function(response)
    {
      var result = [];
      response.on('data', function (chunk)
      {
        result.push(chunk);
      });

      response.on('end', function ()
      {
        console.log("LOCAL END" + result);
      });
    }

    var req = http.request(options, callback);


    req.write(JSON.stringify(
    { 
        customer: 'customer',
        deviceIndicator: 'id',
        userId: 'id2',
        lastVersion: 999 
    }), 'utf8' , 
    function(data)
    {
        console.log('flushed: ' + data);
    });
    req.end();

    console.log(" - trying to post to example - done" );

但是,如果我要添加以下虛擬呼叫,那么我將從本地服務器得到預期的答復:

    var options1 = {
      hostname: 'www.google.com',
      port: '80',
      path: '/',
      headers: {'cache-control': 'no-cache'}
    };

    callback1 = function(response1) {
      var str = ''
      response1.on('data', function (chunk) {
        str += chunk;
      });

      response1.on('end', function () {
        console.log("GOOGLE END" + str);
      });
    }

    var req1 = http.request(options1, callback1);
    req1.end();

    console.log("sent to google - done");

我究竟做錯了什么?

確保192.168.1.134:8082可以訪問並且響應(使用瀏覽器,curl或wget),然后嘗試添加content-length標頭:

var http = require('http');

var payload = JSON.stringify({ 
  customer: 'customer',
  deviceIndicator: 'id',
  userId: 'id2',
  lastVersion: 999 
});

var options = {
  hostname: '192.168.1.134',
  port: 8082,
  path: '/api',
  method: 'POST',
  headers: {
    'content-length': Buffer.byteLength(payload), // <== here
    'content-type': 'application/json',
    'cache-control': 'no-cache'
  }
};

var req = http.request(options, function(response) {
  var result = [];

  response.on('data', function(chunk) {
    result.push(chunk);
  });

  response.on('end', function () {
    console.log('LOCAL END' + result);
  });
});

req.write(payload);
req.end();

最終,我發現問題出在設備本身上,它有某種問題。.當將http請求發送到直接ip地址時,什么都沒有發生,但是當發送到需要dns服務器的地址時,它卻在工作...

不幸的是,我沒有關於此錯誤的任何其他信息。

暫無
暫無

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

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