url 网址解析

在例如编写一个HTTP服务这种场景下如何从请求URL中解析出请求参数是个比较麻烦的事情(如果只使用Node.js的核心模块而不使用任何框架),自己实现这个功能免不了要编写一些令人费解、充满Bug的正则表达式,这种做法生产环境很容易造成安全漏洞。Node.js提供了一个url核心模块,可以用来解析标准的「网络资源定位器」(也就是俗称的网址、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中的内容按照规则解析好了,我们直接使用即可。

作者:Gacfox
版权声明:本网站为非盈利性质,文章如非特殊说明均为原创,版权遵循知识共享协议CC BY-NC-ND 4.0进行授权,转载必须署名,禁止用于商业目的或演绎修改后转载。
Copyright © 2017-2024 Gacfox All Rights Reserved.
Build with NextJS | Sitemap