实例代码test.js
var http=require('http');
var url=require('url');
var querystring=require('querystring'); http.createServer(function(request, response) {
var urlStr = request.url;
var methodName = urlStr.substring(1, urlStr.indexOf('?'));
console.log('methodName:' + methodName);
var arg = url.parse(request.url).query;
var params = querystring.parse(arg);
var code = params.code;
var name = params.name;
console.log('code:' + code +',name:' + name);
}).listen(3000);
console.log("node server start ok port=" + 3000);
运行curl "http://localhost:3000/getName?code=abc&name=test",输出结果如下所示:
[app@VM_34_145_centos tool]$ node test.js
node server start ok port=
url:/getName?code=abc&name=test
methodName:getName
code:abc,name:test
总结
1.node.js获取url参数先引入url和querystring两个模块
2.用url.parse方法将url字符串转化为对象,并获取该对象的query属性(参数列表的字符串)
3.用querystring.parse方法将‘参数列表的字符串’转化为参数列表的对象
4.获取对象中对应参数的值
参考文章:https://blog.csdn.net/m0_38082783/article/details/78194877