nodejs中url 模块

url 模块作用

url 模块 : 对url地址进行解析
nodejs 路由: url 访问的地址

引入url模块

const url = require('url');
const path = 'https://baike.baidu.com/item/MIME/2900607?fr=aladdin&pwd=123456#3'

解析url地址url .parse()

解析url地址 通过url.parse() 方法进行解析
let res = url.parse(path);
第一个参数是要解析的路径 第二个参数 是对 query 字段转换为对象形式; 布尔值 true

let res = url.parse(path, true);
console.log(res);

在这里插入图片描述如果不写true就会输出如下

在这里插入图片描述

protocol: ‘https:’, // 协议
slashes: true,
auth: null,
host: ‘baike.baidu.com’, // 主机名
port: null, // 端口号
hostname: ‘baike.baidu.com’, // 主机名
hash:’#3’, // hash 哈希值 url地址中 #开始往后的内容
search: ‘?fr=aladdin’, // 搜索 url 地址中 ?开始往后的内容 但是不包含hash
query: ‘fr=aladdin’, // 查询 属于search的一部分 是 ? 后边的内容
pathname: ‘/item/MIME/2900607’, // 访问的地址 主机名后边 ? 前边的 中间部分的内容

path: ‘/item/MIME/2900607?fr=aladdin’, // 路径
href: ‘https://baike.baidu.com/item/MIME/2900607?fr=aladdin’ // url地址

在这里插入图片描述这是官方的图片
在这里插入图片描述

实例演示

当你在客户端搜索 localhost:3000 查询地址为zhao时输出123
并且无论有没有查询到,都在服务器会显示pathname也就是你请求的内容

const http = require('http');
const url = require('url');
http.createServer((req,res)=>{
    
    
   // 解析url地址 通过url.parse() 方法进行解析
  let   pathname= url.parse(req.url).pathname;
  if(pathname=='/zhao'){
    
    
    res.write('123');
    res.end();
  }
  console.log(pathname);//在服务器会显示pathname也就是你请求的内容
}).listen(3000,()=>{
    
    
    console.log('服务器开启');//测试服务器知道开启了
})

猜你喜欢

转载自blog.csdn.net/z18237613052/article/details/114948492