如何利用网站策划做好网站建设,申请域名要多少钱,郑州官方通报,网站界面诊断几乎每门编程语言都会包括网络这块,Node.js也不例外。今天主要是熟悉下Node.js中HTTP服务。其实HTTP模块是相当低层次的#xff0c;它不提供路由、cookie、缓存等,像Web开发中不会直接使用,但还是要熟悉下#xff0c;这样也方便以后的学习。 一、统一资源标识符URL 这个是非常…几乎每门编程语言都会包括网络这块,Node.js也不例外。今天主要是熟悉下Node.js中HTTP服务。其实HTTP模块是相当低层次的它不提供路由、cookie、缓存等,像Web开发中不会直接使用,但还是要熟悉下这样也方便以后的学习。 一、统一资源标识符URL 这个是非常常见的,在Node.js中有几种处理。 http://user:passhost.com:80/resource/path/?querystring#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 urlrequire(url);
var urlStrhttp://user:passhost.com:80/rseource/path?querystring#hash;
//parse(urlStr,[parseQueryString],[slashesDenoteHost])
//parseQueryString 布尔值 true:URL查询字符串部分解析为对象字面量默认false
//slashesDenoteHost 布尔值 true:把格式为//host/path的URL解析为:{host:host,pathname:/path},而不是{pathname://host/path} 默认false
var urlObjurl.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: ?querystring,query: { query: string },pathname: /rseource/path,path: /rseource/path?querystring,href: http://user:passhost.com:80/rseource/path?querystring#hash }Process finished with exit code 0 2.URL重定向resolve 有时候请求的url和实际的物理地址并不一样这就要进行虚拟地址和物理地址的转换。 var urlrequire(url);
var originalUrlhttp://user:passhost.com:80/rseource/path?querystring#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:passhost.com:80/another/path?querynewProcess finished with exit code 0 3.处理查询字符串和表单参数 在做web开发中常常需要向服务端get 、post请求请求的时候可能会带一些参数需要对参数进行处理.比如:查询字符串转js对象或js对象转字符串。 这里要用到queryString模块的parse()和stringify()函数。 var qStringrequire(querystring)
//QueryString.parse QueryString.decode function(qs, sep, eq, options)
//1.qs 字符串
//2.sep 使用的分隔符 默认
//3.ep 使用的运算符 默认
//4.一个具有maxKey属性的对象 能够限制生成的对象可以包含的键的数量默认1000,0则无限制
var paramsqString.parse(namecuiyanweicolorredcolorblue);
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 ] }
namecuiyanweicolorredcolorblueProcess finished with exit code 0 转载于:https://www.cnblogs.com/5ishare/p/5323101.html