在例如编写一个HTTP服务这种场景下如何从请求URL中解析出请求参数是个比较麻烦的事情(如果只使用Node.js的核心模块而不使用任何框架),自己实现这个功能免不了要编写一些令人费解、充满Bug的正则表达式,这种做法生产环境很容易造成安全漏洞。Node.js提供了一个url
核心模块,可以用来解析标准的「网络资源定位器」(也就是俗称的网址、URL)。
下面代码中我们解析了一个例子URL,其内容为http://example.com/api/v1/user?userId=3#/hash
。
const url = require('url');
const myUrl = url.parse('http://example.com/api/v1/user?userId=3#/hash');
console.log(myUrl);
运行上面代码输出以下内容:
Url {
protocol: 'http:',
slashes: true,
auth: null,
host: 'example.com',
port: null,
hostname: 'example.com',
hash: '#/hash',
search: '?userId=3',
query: 'userId=3',
pathname: '/api/v1/user',
path: '/api/v1/user?userId=3',
href: 'http://example.com/api/v1/user?userId=3#/hash'
}
我们可以看到url.parse()
方法会把URL中的内容按照规则解析好了,我们直接使用即可。