url模組和querystring模組

來源:互聯網
上載者:User

標籤:

url模組

我們可以使用.parse方法來將一個URL字串轉換為URL對象,樣本如下。

 

1. URL各部分說明

 

var url = require(‘url‘); //載入url模組url.parse(‘http://www.baidu.com‘);

返回的結果為:

{ protocol: ‘http:‘,  slashes: null,  auth: null,  host: null,  port: null, hostname: null, hash: null, search: null, query: null, pathname: ‘www.baidu.com‘, path: ‘www.baidu.com‘, href: ‘http://www.baidu.com‘ }
parse函數的第二個參數是布爾類型,當參數為true時,會將查詢條件query也解析成json格式的對象

parse函數的第三個參數也是布爾類型的,當參數為true,解析時會將url的”//”和第一個”/”之間的部分解析為主機名稱,樣本如下:

var url = require(‘url‘);url.parse(‘http://www.baidu.com/news‘,false,true);

返回的結果:

{ protocol: ‘http:‘,  slashes: true,  auth: null,  host: ‘www.baidu.com‘,  port: null, hostname: ‘www.baidu.com‘, hash: null, search: null, query: null, pathname: ‘/news‘, path: ‘/news‘, href: ‘http://www.baidu.com/news‘ }

protocol: 請求協議
  host: URL主機名稱已全部轉換成小寫, 包括連接埠資訊
  auth:URL中身分識別驗證資訊部分
  hostname:主機的主機名稱部分, 已轉換成小寫
  port: 主機的連接埠號碼部分
  pathname: URL的路徑部分,位於主機名稱之後請求查詢之前
  search: URL 的“查詢字串”部分,包括開頭的問號。
  path: pathname 和 search 連在一起。
  query: 查詢字串中的參數部分(問號後面部分字串),或者使用 querystring.parse() 解析後返回的對象。
  hash: URL 的 “#” 後面部分(包括 # 符號)

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

 

querystring模組

 "QueryString" 模組用於實現URL參數字串與參數對象的互相轉換,來個栗子,如下所示:


 

 

複製代碼代碼如下: var url = require(‘url‘);
 var qs = require(‘querystring‘);
 var queryUrl = "http://localhost:8888/bb?name=bigbear&memo=helloworld" ;
 queryUrl = url.parse(queryUrl).query ;
 console.log(queryUrl) ;
 console.log(qs.parse(queryUrl)) ;

  運行結果·如下:

    name=bigbear&memo=helloworld
    {
      name: ‘bigbear‘,
      memo: ‘helloworld‘
    }

 

 

url模組和querystring模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.