nodejs URL模块操作URL相关方法介绍

网络编程 发布日期:2024/10/7 浏览次数:1

正在浏览:nodejs URL模块操作URL相关方法介绍

url模块

处理HTTP请求时url模块使用率超高,因为该模块允许解析URL、生成URL,以及拼接URL。首先我们来看看一个完整的URL的各组成部分。
复制代码 代码如下:
                         href
 -----------------------------------------------------------------
                            host              path
                      --------------- ----------------------------
 http: // user:pass @ host.com : 8080 /p/a/t/h "codetitle">复制代码 代码如下:
url.parse('http://user:pass@host.com:8080/p/a/t/h"codetitle">复制代码 代码如下:
http.createServer(function (request, response) {
    var tmp = request.url; // => "/foo/bar"
    url.parse(tmp);
    /* =>
    { protocol: null,
      slashes: null,
      auth: null,
      host: null,
      port: null,
      hostname: null,
      hash: null,
      search: '"codetitle">复制代码 代码如下:
url.format({
    protocol: 'http:',
    host: 'www.example.com',
    pathname: '/p/a/t/h',
    search: 'query=string'
});
/* =>
'http://www.example.com/p/a/t/h"codetitle">复制代码 代码如下:
url.resolve('http://www.example.com/foo/bar', '../baz');
/* =>
 
http://www.example.com/baz
 
*/

Query String

querystring模块用于实现URL参数字符串与参数对象的互相转换,示例如下。
复制代码 代码如下:
querystring.parse('foo=bar&baz=qux&baz=quux&corge');
/* =>
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }
*/
 
querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' });
/* =>
'foo=bar&baz=qux&baz=quux&corge='
*/