nodejs解析url参数的三种方法

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(?)!==-1) { params = req.url.split("?"); console.log(params); params = params[1].split("&"); for(var $i=0;$i<params.length;$i++) { var myitem = params[$i].split("="); res.write(myitem[0]+"==========="+myitem[1]+"\n"); } } else { res.write(req.url); } res.end();}).listen(8090);

输出结果:

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

输出结果:

这里比较奇怪,最后的两个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("?")[1]); if (myobj) { res.write(myobj.name); res.write(myobj.age); } else { res.write("aaa"); } res.end();}).listen(8090);

输出结果

 

相关文章