- 要解析的url:http://127.0.0.1:8090/?name=cpc&age=21
- 利用js字符串操作函数进行解析
const myserver = require("http");
const urlib = require("url");
var myfs = require("fs");
myserver.createServer(function (req,res){
console.log(req.url);
res.write("there is a game of love"+"\n");
var params ={};
if (req.url.indexOf('?')!==-)
{
params = req.url.split("?");
console.log(params);
params = params[].split("&");
for(var $i=;$i<params.length;$i++)
{
var myitem = params[$i].split("=");
res.write(myitem[]+"==========="+myitem[]+"\n");
}
}
else
{
res.write(req.url);
}
res.end();
}).listen();
输出结果:
- require('url')模块
const myserver = require("http");
const urlib = require("url");
myserver.createServer(function (req,res){
var myobj = urlib.parse(req.url,true);
var name = myobj.query.name;
var age = myobj.query.age;
var name = myobj.query.name;
console.log(age);
console.log(name);
res.write("aaa");
res.end();
}).listen();
输出结果:
这里比较奇怪,最后的两个undefined其实还是分别输出name和age字段,但由于内存已经释放,所以输出了undefined
- querystring
const myserver = require("http");
const querystring = require("querystring");
var age=null;
var name =null;
myserver.createServer(function (req,res){
var myobj = querystring.parse(req.url.split("?")[]); if (myobj)
{
res.write(myobj.name);
res.write(myobj.age);
}
else
{
res.write("aaa");
}
res.end();
}).listen();
输出结果