2011-06-17 46 views

回答

17

連接當客戶端連接到HTTP服務器的「connection」事件被髮射並提供給回調函數的參數是,其具有所謂的'屬性net.Socket類型的流remoteAddress'。同樣,傳遞給你的請求收聽每個HTTP請求也具有參考連接對象:在URL通過嵌入憑據

var http = require('http'); 
var server = http.createServer(function (req, res) { 
    res.writeHead(200, {'Content-Type': 'text/plain'}); 
    res.end('Hello ' + req.connection.remoteAddress + '!'); 
    // Client address in request -----^ 
}); 
server.on('connection', function(sock) { 
    console.log('Client connected from ' + sock.remoteAddress); 
    // Client address at time of connection ----^ 
}); 
server.listen(9797); 

至於認證,我不認爲這種形式是可靠的,some web browsers do not pass on the information在HTTP請求(IE和Chrome至少)。您最好實施基於HTTP標準的身份驗證方案,如Basic access authDigest access auth

3

對於HTTP基本/摘要式身份驗證,您可以使用http-auth模塊

// Authentication module. 
var auth = require('http-auth'); 
var basic = auth.basic({ 
    realm: "Simon Area.", 
    file: __dirname + "/../data/users.htpasswd" // gevorg:gpass, Sarah:testpass ... 
}); 

// Creating new HTTP server. 
http.createServer(basic, function(req, res) { 
    res.end("Welcome to private area - " + req.user + "!"); 
}).listen(1337); 
相關問題