2011-04-17 65 views

回答

3
var options = { 
    host: 'www.google.com', 
    port: 80, 
    path: '/upload', 
    method: 'POST', 
    headers: ... 
}; 

var req = http.request(options, function(res) { 
    console.log('STATUS: ' + res.statusCode); 
    console.log('HEADERS: ' + JSON.stringify(res.headers)); 
    res.setEncoding('utf8'); 
    res.on('data', function (chunk) { 
    console.log('BODY: ' + chunk); 
    }); 
}); 

http.request文檔。

基本上,您可以使用方法向主機/端口+路徑請求散列意見。然後處理來自該服務器的響應。

+0

我相信他正在嘗試創建一個HTTP服務器,而不是客戶端。 – igorw 2011-04-17 13:24:44

+0

謝謝。我這樣做,但是當我創建JSON字符串時,值傳遞錯誤,請參閱:http://stackoverflow.com/questions/5693247/node-js-create-json-and-post-to-postbin – donald 2011-04-17 13:24:58

+0

@igorw他想要POST到節點中的URL。 – Raynos 2011-04-17 13:25:42

1

從Node.js的主頁:

var http = require('http'); 
http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello World\n'); 
}).listen(8124, "127.0.0.1"); 
console.log('Server running at http://127.0.0.1:8124/'); 

您可以訪問REQ對象來獲得數據。

對於更高層次的方法,請查看express.js

你可以做這樣的事情:

var app = express.createServer(); 

app.post('/', function(req, res){ 
    res.send('Hello World'); 
}); 

app.listen(3000); 
+0

我需要服務器還是客戶端?我不明白爲什麼我需要創建一個服務器到POST。謝謝 – donald 2011-04-17 21:17:12

+0

@唐納德你沒有。您需要一臺服務器來處理傳入的數據。你想發佈數據到另一臺服務器,所以這個答案是不相關的。 – Raynos 2011-04-17 22:39:55

+0

原始問題不明確。我以爲他在問如何接收HTTP POST。 – kcbanner 2011-04-23 05:41:20

0

我強烈推薦Node.js的模塊restler

rest.post('http://user:[email protected]/action', { 
    data: { id: 334 }, 
}).on('complete', function(data, response) { 
    if (response.statusCode == 201) { 
     // you can get at the raw response like this... 
    } 
});