幾乎每門編程語言都會包括網絡這塊,Node.js也不例外。今天主要是熟悉下Node.js中HTTP服務。其實HTTP模塊是相當低層次的,它不提供路由、cookie、緩存等,像Web開發中不會直接使用,但還是要熟悉下,這樣也方便以后的學習。
一、統一資源標識符URL
這個是非常常見的,在Node.js中有幾種處理。
http://user:pass@host.com:80/resource/path/?query=string#hash
協議://身份認證@主機名.com:端口/路徑/搜索/查詢#散列
在URL模塊中可以URL定義的屬性和方法
exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat;exports.Url = Url;function Url() {this.protocol = null;this.slashes = null;this.auth = null;this.host = null;this.port = null;this.hostname = null;this.hash = null;this.search = null;this.query = null;this.pathname = null;this.path = null;this.href = null; }
上面代碼可以看到URL模塊定義了protocol、slashes等這些屬性,還有parse、resolve 等方法.
1、URL字符串轉URL對象 parse
/*** Created by Administrator on 2016/3/26.*/ var url=require('url'); var urlStr='http://user:pass@host.com:80/rseource/path?query=string#hash'; //parse(urlStr,[parseQueryString],[slashesDenoteHost]) //parseQueryString 布爾值 true:URL查詢字符串部分解析為對象字面量默認false //slashesDenoteHost 布爾值 true:把格式為//host/path的URL解析為:{host:'host',pathname:'/path'},而不是{pathname:'//host/path'} 默認false var urlObj=url.parse(urlStr,true,false); console.log(urlObj);
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe URL.js Url {protocol: 'http:',slashes: true,auth: 'user:pass',host: 'host.com:80',port: '80',hostname: 'host.com',hash: '#hash',search: '?query=string',query: { query: 'string' },pathname: '/rseource/path',path: '/rseource/path?query=string',href: 'http://user:pass@host.com:80/rseource/path?query=string#hash' }Process finished with exit code 0
2.URL重定向resolve
有時候請求的url和實際的物理地址并不一樣,這就要進行虛擬地址和物理地址的轉換。
?
var url=require('url'); var originalUrl='http://user:pass@host.com:80/rseource/path?query=string#hash'; var newResource='/another/path?querynew'; console.log(url.resolve(originalUrl,newResource));
?
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe URL.js http://user:pass@host.com:80/another/path?querynew Process finished with exit code 0
?
3.處理查詢字符串和表單參數
在做web開發中常常需要向服務端get 、post請求,請求的時候可能會帶一些參數,需要對參數進行處理.比如:查詢字符串轉js對象或js對象轉字符串。
這里要用到queryString模塊的parse()和stringify()函數。
var qString=require('querystring') //QueryString.parse = QueryString.decode = function(qs, sep, eq, options) //1.qs 字符串 //2.sep 使用的分隔符 默認& //3.ep 使用的運算符 默認= //4.一個具有maxKey屬性的對象 能夠限制生成的對象可以包含的鍵的數量默認1000,0則無限制 var params=qString.parse("name=cuiyanwei&color=red&color=blue"); console.log(params); //QueryString.stringify = QueryString.encode = function(obj, sep, eq, options) console.log(qString.stringify(params,"&","="));
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe URL.js { name: 'cuiyanwei', color: [ 'red', 'blue' ] } name=cuiyanwei&color=red&color=blueProcess finished with exit code 0
?