2016-06-23 25 views
-2

我需要將數據從我的NodeJS服務器發送到外部服務器。我已經嘗試了很多代碼並且搜索了很多,但是沒有得到任何適當的工作示例或者它不適用於我的情況。如何從nodeJS向外部發送數據?

這裏是我的代碼:

app.get('/getFrom', function (req, res) { 
var request = require('request'); 

     // Try 1 - Fail 
     /*var options = { 
     url: 'http://example.com/synch.php', 
     'method': 'POST', 
     'body': {"nodeParam":"working"} 

     }; 
     request(options, callback); 
     */ 

     // Try 2 - Fail 
     /* request({ 
      // HTTP Archive Request Object 
      har: { 
       url: 'http://example.com/synch.php', 
       method: 'POST', 
       postData: { 
       params: [ 
        { 
        nodeParam: 'working' 
        } 
       ] 
       } 
      } 
      },callback)*/ 

    function callback(error, response, body) { 
     if (!error && response.statusCode == 200) { 
      console.log("body " + body); // Show the HTML for the Google homepage. 
       res.send(body); 
     } 
     else{ 
      console.log("Error " + error); 
      res.send(error); 
     } 
    } 

/* ------ HTTP ------ */

var postData = querystring.stringify({ 
    'nodeParam' : 'Hello World!' 
}); 

// try 3 - Fail 
/*var optionsHTTP = { 
    hostname: 'http://example.com', 
    port: 80, 
    path: '/synch.php', 
    method: 'POST', 
    headers: { 
    'Content-Type': 'application/x-www-form-urlencoded', 
    'Content-Length': Buffer.byteLength(postData) 
    } 
}; 

var req1 = http.request(optionsHTTP, function(res1){ 
    console.log('STATUS: ' + res1.statusCode); 
    console.log('HEADERS: ' + JSON.stringify(res1.headers)); 
    res1.setEncoding('utf8'); 
    res1.on('data', function(chunk){ 
    console.log('BODY: ' + chunk); 
    }); 
    res1.on('end', function(){ 
    console.log('No more data in response.') 
    }) 
}); 

req1.on('error',function(e){ 
    console.log('problem with request:' + e.message); 
}); 

// write data to request body 
req1.write(postData); 
req1.end();*/ 

/* ------/HTTP ------ */

請讓我知道我錯了

+0

簡化你的問題。選擇你的一個嘗試,列出代碼並告訴我們爲什麼失敗。你得到什麼錯誤信息? – MrWillihog

+0

你是否啓動了一個http服務器?看看[Express.js](http://expressjs.com/) – jhhayashi

回答

0

我找到了工作和測試的解決方案:



    request({ 
     url: 'http://example.com/synch.php', //URL to hit 
     qs: {nodeParam: 'blog example', xml: xmlData}, //Query string data 
     method: 'POST', //Specify the method 
    },callback); 

0

不知道到底爲什麼你的要求可能會失敗,但這是一個簡單而直接的樣本關於使用request模塊中NPM:

var request = require('request'); 
 

 
var postData = { 
 
\t name: 'test123' 
 
} 
 

 
request({ 
 
\t url: 'http://jsonplaceholder.typicode.com/posts', 
 
\t method: 'POST', 
 
\t data: JSON.stringify(postData) 
 
}, function(err, response) { 
 
\t if (err) { 
 
\t \t return console.error(err); 
 
\t }; 
 

 
\t console.log(JSON.stringify(response)); 
 
})

這個片段使得到靜止API的請求,並且在控制檯上顯示的結果。響應數據可在response.body屬性中找到。

+0

其實我試圖通過NodeJs發佈一些數據需要外部URL .. – eweb

+0

我已更新示例以反映更改。我想這就是你想要做的。如果您從服務器收到錯誤,很可能是由於jsonplaceholder.typicode.com存在問題,而不是node.js代碼本身 –