DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> JavaScript綜合知識 >> nodejs URL模塊操作URL相關方法介紹
nodejs URL模塊操作URL相關方法介紹
編輯:JavaScript綜合知識     

 這篇文章主要介紹了nodejs URL模塊操作URL相關方法介紹,本文講解了parse方法、format方法、querystring方法等,需要的朋友可以參考下

   

url模塊

處理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方法來將一個URL字符串轉換為URL對象,示例如下。
代碼如下:
url.parse('http://user:[email protected]: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: 'http://user:[email protected]: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方法允許將一個URL對象轉換為URL字符串,示例如下。

代碼如下:
url.format({
protocol: 'http:',
host: 'www.example.com',
pathname: '/p/a/t/h',
search: 'query=string'
});
/* =>
'http://www.example.com/p/a/t/h?query=string'
*/
另外,.resolve方法可以用於拼接URL,示例如下。
代碼如下:
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='
*/
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved