2012-04-20 13 views

risposta

20

È necessario collegare il modulo 'url'

var http = require('http'); 
var url = require('url') ; 

http.createServer(function (req, res) { 
    var hostname = req.headers.host; // hostname = 'localhost:8080' 
    var pathname = url.parse(req.url).pathname; // pathname = '/MyApp' 
    console.log('http://' + hostname + pathname); 

    res.writeHead(200); 
    res.end(); 
}).listen(8080); 

UPD:

Nel modulo url Node.js v8 ottenere nuove API per lavorare con gli URL. Vedere documentation:

Nota: Durante l'API Legacy non è stato deprecato, si è mantenuto solo per compatibilità con le applicazioni esistenti. Il nuovo codice dell'applicazione deve utilizzare l'API WHATWG.

+5

req.headers può essere falsificato dall'utente che effettua la richiesta, stai attento a fidarti di esso. –

0

Per ottenere i dettagli dell'URL nelle app del nodo. Devi usare il modulo URL. Modulo URL dividerà il vostro indirizzo web in parti leggibili

In seguito ho dato il codice

var url = require('url'); 
var adr = 'http://localhost:8080/default.htm?year=2017&month=february'; 
var q = url.parse(adr, true); 

console.log(q.host); //returns 'localhost:8080' 
console.log(q.pathname); //returns '/default.htm' 
console.log(q.search); //returns '?year=2017&month=february' 

var qdata = q.query; //returns an object: { year: 2017, month: 'february' } 
console.log(qdata.month); //returns 'february'`enter code here` 

Per saperne di più su modulo URL si può visitare https://nodejs.org/api/url.html

Problemi correlati