![](/img/trans.png)
[英]http request from node.js local server port 5000 to 8000 gives error
[英]Listen and request from same port in node.js
我正在測試在 node.js 中設置的 XML-RPC,並想測試服務器接收調用和響應以及客戶端調用服務器並在同一節點 session 中接收響應。 如果我使用相同的主機和端口運行 http.createServer 和 http.request ,我會得到:
Error: ECONNREFUSED, Connection refused
at Socket._onConnect (net.js:600:18)
at IOWatcher.onWritable [as callback] (net.js:186:12)
將生成錯誤的測試代碼:
var http = require('http')
var options = {
host: 'localhost'
, port: 8000
}
// Set up server and start listening
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('success')
}).listen(options.port, options.host)
// Client call
// Gets Error: ECONNREFUSED, Connection refused
var clientRequest = http.request(options, function(res) {
res.on('data', function (chunk) {
console.log('Called')
})
})
clientRequest.write('')
clientRequest.end()
雖然如果將上面的代碼分成兩個文件並作為單獨的節點實例運行,上面的代碼將起作用,有沒有辦法讓上面的代碼在同一個節點實例上運行?
正如上面提到的,您的 http-server 在您發出請求時可能沒有運行。 使用setTimeout
是完全錯誤的。 在listen
方法中使用回調參數:
var http = require('http')
var options = {
host: 'localhost'
, port: 8000
}
// Set up server and start listening
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('success')
}).listen(options.port, options.host, function() {
// Client call
// No error, server is listening
var clientRequest = http.request(options, function(res) {
res.on('data', function (chunk) {
console.log('Called')
})
})
clientRequest.write('')
clientRequest.end()
});
您的 HTTP 服務器在您向其發出請求時可能尚未完全加載和運行。 嘗試使用 setTimeout 包裝您的客戶端請求,讓您的服務器有時間進行設置,例如:
var http = require('http')
var options = {
host: 'localhost'
, port: 8000
}
// Set up server and start listening
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('success')
}).listen(options.port, options.host)
setTimeout(function() {
// Client call
// Shouldn't get error
var clientRequest = http.request(options, function(res) {
res.on('data', function (chunk) {
console.log('Called')
})
})
clientRequest.write('')
clientRequest.end()
}, 5000);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.