当前位置:首页> 正文

Node.js中的HTTP模块与URL模块

Node.js中的HTTP模块与URL模块

几乎每门编程语言都会包括网络这块,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=blue

Process finished with exit code 0

展开全文阅读

相关内容