2016-04-05 112 views
0

如何將request.url顯示在console.log中以查看某人稱爲哪個網址? 所以我想看看每個調用與控制檯的網址。使用node.js將控制檯顯示到控制檯中

對不起,我是一個非常初學node.js ;-) 感謝您的幫助。

//Lets require/import the HTTP module 
var http = require('http'); 

//Lets define a port we want to listen to 
const PORT=8083; 

//We need a function which handles requests and send response 
function handleRequest(request, response){ 
    response.end('It Works!! Path Hit: ' + request.url); 
} 

//Create a server 
var server = http.createServer(handleRequest); 

//Lets start our server 
server.listen(PORT, function(){ 
    //Callback triggered when server is successfully listening. Hurray! 
    console.log("Server listening on: http://localhost:%s", PORT); 
    console.log("URL:%s"); 
}); 
+3

你只是爲了尋找答案,「把'執行console.log(request.url)'內你的'handleResponse'函數「? – apsillers

回答

2

如果您使用快遞,您可以設置一個自定義中間件,爲每個請求調用。

// logging middleware 
 
var num = 0; 
 
app.use(function (req, res, next) { 
 
    var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress; 
 
    var method = req.method; 
 
    var url = req.url; 
 

 
    console.log((++num) + ". IP " + ip + " " + method + " " + url); 
 
    next(); 
 
});

但是你可以做同樣的你的HTTP模塊服務器:)