Node.js3---nodejs的内置模块之url模块
url模块
旧版写法url.parse( )、url.format( )和url.resolve( )
url.parse( )
url.parse( )可以解析类似于字符串类的地址,比如我们想截取地址的参数就可以直接用它,不需要我们自己写js去截取,如下例
代码如下:
const url = require('url')
const urlString = 'https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110'
const parsedStr = url.parse(urlString)
console.log(parsedStr)
由于我们每次编写完node代码后都要保存重启服务器,这里我们可以安装一个小工具,就不需要每次重复执行命令来重启服务,安装命令如下:
npm i -g nodemon
安装了它之后,我们在每次保存完编辑后的代码就自动的重启服务器,非常方便。
如下图所示,我们启动服务器后,地址栏输入http://localhost:3000/api/list就能看到列表页:
代码如下图所示,通过require导入放在module文件夹下的两个自定义模块,引入http和url两个内置模块:
代码如下:
//====4url模块.js====
//内置模块--http模块
const http = require('http')
const url = require('url')
var moduleRenderStatus = require('./module/renderStatus')
var moduleRenderHTML = require('./module/renderHTML')
//创建本地服务器
http.createServer((req, res) => {
//req是接收浏览器传过来的参数,res是返回给浏览器的内容
if (req.url === "/favicon.ico") {
//todo 读取本地图标
return
}
console.log(url.parse(req.url))
var pathname = url.parse(req.url).pathname;
res.writeHead(moduleRenderStatus.renderStatus(pathname), { "Content-Type": 'text/html;charset=utf-8' })
res.write(moduleRenderHTML.renderHTML(pathname))
res.end()
}).listen(3000, () => {
console.log("开启服务器")
})
//===renderHTML.js====
function renderHTML(url) {
switch (url) {
case '/api/home':
return `<html><b>首页</b></html>`
case '/api/list':
return `<html><b>列表页</b></html>`
case '/detail':
return `<html><b>详情页</b></html>`
default:
return `<html><b>404页 not find</b></html>`
}
}
module.exports = {
renderHTML
}
//=====renderStatus.js====
function renderStatus(url) {
var arr = ["/home", "/list", "/api/home", "/api/list"]
return arr.includes(url) ? 200 : 404
}
exports.renderStatus = renderStatus
我们在4url模块.js里打印了url.parse(req.url) 可以在终端里看到它是一个对象,里面
当我们在地址栏输入http://localhost:3000/api/list?name=xiaoming&age=27的时候,也就是给api传参数的时候,这个时候我们在终端能看到如下效果:
假如说我们想要一个{ “name”:“xiaoming”, “age”:“27” }这样的一个json对象,那这个时候就可以用上url.parse的第二个参数了,如下图,我们给第二个参数传为true,再在终端打印看结果:
我们可以看到此时又多了一个query对象,这前面的[Object: null prototype]表示类型,不用管,它的后面是一个我们想要的对象,可以直接取用,像我们这里直接通过urlobj.query.name就取到xiaoming
url.format( )
既然可以将字符串解析成对象,那对象自然可以拼接回字符串,这里用到我们的url模块的url.format( )方法,如下例:
代码如下:
const url = require('url')
const urlObject = {
protocol: 'https:',
slashes: true,
auth: null,
host: 'www.baidu.com:443',
port: '443',
hostname: 'www.baidu.com',
hash: '#tag=110',
search: '?id=8&name=mouse',
query: { id: '8', name: 'mouse' },
pathname: '/ad/index.html',
path: '/ad/index.html?id=8&name=mouse'
}
const parsedObj = url.format(urlObject)
console.log(parsedObj)
url.resolve( )
url.resolve可以进行字符串的拼接,主要用于地址的拼接和格式化。如下例:
代码如下:
const url = require('url')
var a = url.resolve('/one/two/three', 'four')
var b = url.resolve('http://example.com/', '/one')
var c = url.resolve('http://example.com/one', '/two')
var d = url.resolve('http://example.com/one/12/34', '/56')
var e = url.resolve('http://example.com/one/12/34', '56')
// 需要注意的是, /one/two/three这种纯路径注意加/和不加/是有区别的,不加/会用后面的一个把前面的一个进行替换,加/就会进行相连
// 如果是http://example.com/这种域名形式的,则会后面的替换前面的
console.log(a)
console.log(b)
console.log(c)
console.log(d)
console.log(e)
新版写法
new URL( )
如下例,获取设置URL的主机(host)部分:
代码如下:
// url新版写法
const { URL } = require('url');
const myURL = new URL('https://example.org:81/foo');
console.log(myURL.host);
再来看个例子:
打印出myURL是个对象,代码如下:
// url新版写法
const http = require('http')
const { URL } = require('url');
//创建本地服务器
http.createServer((req, res) => {
//req是接收浏览器传过来的参数,res是返回给浏览器的内容
const myURL = new URL(req.url, 'http://127.0.0.1:3000');
console.log("myURL是", myURL)
console.log(myURL.searchParams.get('a'))
for (var [key, value] of myURL.searchParams) {
console.log(key, value)
}
}).listen(3000, () => {
console.log("开启服务器")
})