Nodejs獲取url路徑中的各個引數

admin發表於2017-05-10

分享一段程式碼例項,它實現了利用nodejs獲取url傳遞的引數的功能。

程式碼例項如下:

[JavaScript] 純文字檢視 複製程式碼
// http://127.0.0.1:3000/select?name=peng&id=29
var http = require('http');
var server = http.createServer(function(req,res){
    var pathname = url.parse(req.url).pathname;//pathname => select
    var arg = url.parse(req.url).query;//arg => name=peng&id=29
    console.log("Request for " + arg );
    var str = querystring.parse(arg);//str=> {name:'peng',id:'29'}
    var arg1 = url.parse(req.url, true).query;//arg1 => {name:'peng',id:'29'}
    console.log("Request for " + arg1 );
    var name = querystring.parse(arg).name;//name => peng
    console.log("name = "+name);
    console.log("Request for " + pathname + " received.");
});
server.listen(3000,'127.0.0.1');

相關文章