nodejs解析url参数的三种方法

时间:2022-08-14 11:57:04
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();

输出结果:

nodejs解析url参数的三种方法

  • 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();

输出结果:

nodejs解析url参数的三种方法

这里比较奇怪,最后的两个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();

输出结果

nodejs解析url参数的三种方法