nodejs入门教程12:nodejs url模块

一、引入URL模块

要使用URL模块,首先需要引入它。你可以使用require方法来引入URL模块:

const url = require('url');

二、URL模块的方法

URL模块提供了几个主要的方法来处理URL,包括url.parse()url.format()url.resolve()等。

  1. url.parse(urlString, parseQueryString, slashesDenoteHost)

    • 功能:解析URL字符串,并返回一个URL对象。
    • 参数
      • urlString(字符串):要解析的URL字符串。
      • parseQueryString(布尔值,可选):如果为true,则查询字符串(query string)会被解析成一个对象。默认为false
      • slashesDenoteHost(布尔值,可选):如果为true,则//foo/bar形式的字符串会被解析为{ host: 'foo', pathname: '/bar' }。默认为false
    • 返回值:一个包含URL各部分的对象。
    const myUrl = url.parse('http://example.com/pathname/?search=test#hash', true);
    console.log(myUrl);
    

    输出结果会是一个对象,包含URL的协议、主机名、端口、路径名、查询字符串(已解析为对象)、哈希值等。

  2. url.format(urlObject)

    • 功能:根据一个URL对象生成URL字符串。
    • 参数
      • urlObject(对象):包含URL各部分的对象。
    • 返回值:一个格式化的URL字符串。
    const myUrl = url.format({
          
          
      protocol: 'http:',
      hostname: 'example.com',
      port: 8080,
      pathname: '/pathname/',
      search: '?search=test',
      hash: '#hash'
    });
    console.log(myUrl);
    

    输出结果会是一个格式化的URL字符串。

  3. url.resolve(from, to)

    • 功能:解析一个相对于基础URL的目标URL。
    • 参数
      • from(字符串):基础URL。
      • to(字符串):要解析的目标URL。
    • 返回值:一个解析后的URL字符串。
    const myUrl = url.resolve('http://example.com/one/', '/two');
    console.log(myUrl);
    

    输出结果会是一个解析后的URL字符串,其中目标URL相对于基础URL进行了解析。

三、URLSearchParams对象

从Node.js 10开始,URL模块还提供了一个URLSearchParams类,用于处理URL查询字符串。

  1. 构造函数new URLSearchParams([init])

    • 功能:创建一个URLSearchParams对象。
    • 参数
      • init(可选):一个字符串或一个对象,用于初始化查询字符串。
  2. 方法

    • append(name, value):添加一个查询参数。
    • delete(name):删除一个查询参数。
    • get(name):获取一个查询参数的值。
    • getAll(name):获取一个查询参数的所有值(如果存在多个值)。
    • has(name):检查是否存在一个查询参数。
    • set(name, value):设置一个查询参数的值。
    • sort():对查询参数进行排序。
    • toString():将查询字符串转换为字符串。
    • forEach(callback[, thisArg]):遍历查询参数。
    • keys():返回一个迭代器,用于遍历查询参数的名称。
    • values():返回一个迭代器,用于遍历查询参数的值。
    • entries():返回一个迭代器,用于遍历查询参数的键值对。

四、示例代码

以下是一个使用URL模块和URLSearchParams对象的示例代码:

const url = require('url');

// 解析URL
const myUrl = url.parse('http://example.com/pathname/?search=test#hash', true);
console.log(myUrl);

// 格式化URL
const formattedUrl = url.format(myUrl);
console.log(formattedUrl);

// 解析相对URL
const resolvedUrl = url.resolve('http://example.com/one/', '/two');
console.log(resolvedUrl);

// 使用URLSearchParams
const params = new URLSearchParams('search=test&foo=bar');
console.log(params.toString()); // "search=test&foo=bar"

params.append('baz', 'qux');
console.log(params.toString()); // "search=test&foo=bar&baz=qux"

params.set('foo', 'newvalue');
console.log(params.toString()); // "search=test&foo=newvalue&baz=qux"

console.log(params.get('foo')); // "newvalue"

五、总结

Node.js的URL模块提供了强大的功能来处理URL,包括解析、构建、编码、解码等。通过掌握这些功能,你可以更方便地处理URL相关的任务,在开发Web应用时更加得心应手。

猜你喜欢

转载自blog.csdn.net/gusushantang/article/details/143452216