nodejs是目前比较流行的一种服务端能够运行JavaScript的环境,那么今天分享的是关于http模块的小知识,其实我们知道在php中,我们通过http协议将数据提交到另外的处理页中时我们也同样可以通过server全局函数可以获得一些关于http发送的数据信息,那么在nodejs中也同样,我们也可以获得相关的一些信息,首先要分享的是关于URL对象。
那么我们在提交或者获取一些信息的时候,少不了要用到url,而url在nodejs中可以转换成URL对象,那么我们可以通过parse函数来实现,例如:
url.parse(urlStr, [parseQueryString], [slashesDenoteHost])
urlStr:标示一个url字符串,例如:http://www.asni.cn/index.php?action=reg&token=134232#free
parseQueryString:(可选)布尔值,如果为true,则将urlStr的查询字符串部分解析成对象字面量,例如:action=reg&token=134232解析成{‘action’:’reg’, ‘token’:’134232′},默认为false
slashesDenoteHost:(可选)布尔值,如果为true,则可以将urlStr格式为//host/path的地址解析成{host:’host’, pathname:’/path’},就不会解析成{pathname:’host/path’}这样,默认为false
例如:
var url = require('url'); var urls = 'https://www.asni.cn:8080/tool/index.html?action=reg&tokan=abteasgda3234df#one'; console.log(url.parse(urls)); 解析成如下: { protocol: 'https:', slashes: true, auth: null, host: 'www.asni.cn:8080', port: '8080', hostname: 'www.asni.cn', hash: '#one', search: '?action=reg&tokan=abteasgda3234df', query: 'action=reg&tokan=abteasgda3234df', pathname: '/tool/index.html', path: '/tool/index.html?action=reg&tokan=abteasgda3234df', href: 'https://www.asni.cn:8080/tool/index.html?action=reg&tokan=abteasgda3234 df#one' }
当然,我们可以解析成这样的对象,同样我们也可以将这样的对象还原解析成地址,使用format函数即可。
url.format(urlObj);
例如:
var url = require('url'); var urlObj = { protocol: 'https:', slashes: true, auth: null, host: 'www.asni.cn:8080', port: '8080', hostname: 'www.asni.cn', hash: '#one', search: '?action=reg&tokan=abteasgda3234df', query: 'action=reg&tokan=abteasgda3234df', pathname: '/tool/index.html', path: '/tool/index.html?action=reg&tokan=abteasgda3234df', href: 'https://www.asni.cn:8080/tool/index.html?action=reg&tokan=abteasgda3234df#one' }; console.log(url.format(urlObj)); 解析成如下: https://www.asni.cn:8080/tool/index.html?action=reg&tokan=abteasgda3234df#one
所以这就是http中关于url对象的一些简单说明,算是入门的。
另外url模块还有一个有用的功能就是与浏览器相同的方式来解析URL的组件,这个组件可以让在服务器端操作URL字符串,然后在URL中作出调整。比如,你可能想要在处理一个请求之前更改URL位置,因为该资源已经移动或者更改了参数。那么使用以下语法:
url.resolve(from, to)
from:指定原始基础URL字符串;
to:指定你想要的URL被解析到的新位置。
例如:
var url = require('url'); var oldUrl = 'http://www.asni.cn:80/test/path?query=string#hash'; var newResource = '/another/path?action=reg'; console.log(url.resole(oldUrl, new Resource)); 显示为如下: http://www.asni.cn:80/another/path?action=reg
评论前必须登录!
注册