DIV CSS 佈局教程網

Node.js URL模塊操作URL的相關方法介紹
編輯:JavaScript綜合知識     

在處理HTTP請求時,url模塊的使用率非常高,因為它能解析URL、生成URL以及拼接URL。先看一個完整URL的組成部分:

href
-----------------------------------------------------------------
host                 path
---------------    ----------------------------
http: // user:pass @ host.com : 8080 /p/a/t/h ?query=string #hash
----- --------- -------- ---- -------- ------------- -----
protocol     auth  hostname port pathname  search    hash
------------
query

parse方法

用parse方法可以把URL字符串轉換為URL物件:

url.parse('https://user:pass@host.com:8080/p/a/t/h?query=string#hash');
/* =>
{ protocol: 'http:',
  auth: 'user:pass',
  host: 'host.com:8080',
  port: '8080',
  hostname: 'host.com',
  hash: '#hash',
  search: '?query=string',
  query: 'query=string',
  pathname: '/p/a/t/h',
  path: '/p/a/t/h?query=string',
  href: 'https://user:pass@host.com:8080/p/a/t/h?query=string#hash' }
*/

傳給parse的不一定是完整URL。例如在HTTP服務器回調函數中,request.url並不含協議頭和域名,但同樣能用parse解析:

http.createServer(function (request, response) {
  var tmp = request.url; // => "/foo/bar?a=b"
  url.parse(tmp);
  /* =>
  { protocol: null, slashes: null, auth: null, host: null,
    port: null, hostname: null, hash: null,
    search: '?a=b', query: 'a=b',
    pathname: '/foo/bar', path: '/foo/bar?a=b', href: '/foo/bar?a=b' }
  */
}).listen(80);

parse方法還支援第二、第三個布爾可選參數。第二個參數為true時,回傳的URL物件中query不再是字符串,而是經querystring模塊轉換後的參數物件;第三個參數為true時,能正確解析不帶協議頭的URL,例如//www.example.com/foo/bar。

format方法

反過來,format方法可以把URL物件轉換為URL字符串:

url.format({
  protocol: 'http:',
  host: 'www.example.com',
  pathname: '/p/a/t/h',
  search: 'query=string'
});
/* =>
'https://www.example.com/p/a/t/h?query=string'
*/

resolve方法

resolve方法可用於拼接URL:

url.resolve('https://www.example.com/foo/bar', '../baz');
/* =>
https://www.example.com/baz
*/

querystring模塊

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='
*/

從解析、格式化到拼接,再到查詢串的雙向轉換,url與querystring這兩個模塊幾乎覆蓋了Node.js處理URL時的所有常見場景。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved