- 要解析的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(‘?‘)!==-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);
输出结果
原文地址:https://www.cnblogs.com/saintdingspage/p/11025496.html
时间: 2024-11-05 15:57:35