【Node.js】URL 模块

自动重启服务器的插件nodemon: npm i -g nodemon。或者 node-dev 也可以:npm i -g node-dev

parse,format,resolve 为旧版写法。

parse

js 复制代码
import url from '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)

使用 const parsedStr = url.parse(urlString, true) 时,会将 query 转换为对象的形式:

format

js 复制代码
import url from '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)

resolve

js 复制代码
import url from 'url'
// url.resolve(from, to)
var a = url.resolve('/one/two/three', 'four')
var e = 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/', 'three')
console.log(a + "," + e + "," + b + "," + c + "," + d)

总结一下就是:1. 没有域名的地址,在地址最后一个 / 后进行拼接。2. 有域名的地址,to 含有 / ,直接拼接到域名之后,没有/,拼接到 from 的后面。

新版写法 new URL。

js 复制代码
import http from 'http'
import url from 'url'
// 创建本地服务器接收数据
const server = http.createServer((req, res) => {
  const myUrl = new URL(req.url, 'http://127.0.0.1:3000')
  console.log(myUrl)
  res.writeHead(200, { 
    'Content-Type': 'application/json' 
  })
  res.end(JSON.stringify({
    data: "hello"
  }))
})
server.listen(8000,()=> {
  console.log("server is running")
})
js 复制代码
const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo

查询参数:

js 复制代码
const myURL = new URL('https://example.org/abc?foo=~bar');
console.log(myURL.search);  // ?foo=~bar

其他用法都在官方文档,写的很清楚。Node.js 中文网

相关推荐
FungLeo1 小时前
成为全栈·Node 后端篇·配置管理:环境变量、多环境与密钥安全
node.js·环境变量·多环境配置·密钥安全
FungLeo2 小时前
成为全栈·Node 后端篇·错误处理:异常分层与全局捕获
node.js·错误处理·异常分层·全局捕获·成为全栈
百万运营Pro10 小时前
用 Astro + Supabase 从零构建全网盘聚合搜索引擎:PGroonga 中文检索实战
搜索引擎·前端框架·node.js·个人开发·学习方法·ai编程·资源分享
小婉1 天前
我用 Next.js + React Flow 从零搭建了一个可视化 AI 工作流编排平台
前端·人工智能·node.js
抓不住时间的沙1 天前
N1搭建守护环境以及重装 Armbian 后完整恢复整套守护环境,清理日志步骤
node.js
meilindehuzi_a1 天前
从域名到数据库:React + Node.js 项目部署全流程与用户访问链路
数据库·react.js·node.js
李游Leo1 天前
Node.js 开发环境安装与 npm/pnpm 国内镜像配置(Windows / macOS / Linux)
npm·node.js·pnpm·前端开发·开发环境
阿黎梨梨2 天前
AI也有记忆?LangChain Memory 管理指南
langchain·node.js·llm
小小龙学IT2 天前
libuv 开源异步 I/O 事件循环库深度解析:Node.js 的心脏,C++ 高性能网络程序的引擎
c++·开源·node.js
用户672465366053 天前
Node 守护进程日志转发踩坑记:stdio 管道、UTF-8 截断,和一个字符串按值传参的故事
node.js