【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 中文网

相关推荐
孟陬12 小时前
解决动态 import 类型 Any 痼癖
typescript·node.js·bun
Dumbness12 小时前
后台管理员把自己锁在门外:RBAC 里「自己的权限只能由别人来减」
安全·node.js
攻城狮白玉14 小时前
Node.js 发布紧急安全更新:10 个漏洞,8 枚危险证书被拉黑。附AI修复提示词
node.js
Json____1 天前
用 FastAPI + Vue3 打造一套完整的在线考试系统:从组卷到阅卷的业务闭环实践
后端·node.js·fastapi·it学习·wwwoop.com
Dumbness2 天前
写 MCP 服务器踩的坑:stdout 是协议通道,一行不带换行的日志就能让客户端超时
node.js·mcp
flash俊杰2 天前
ContentPart 联合类型实战:不碰存量消息,怎么给 ChatMessage 加图片
node.js
Json____2 天前
用 Node.js + Vue3 打造一个家居装修 AI 智能咨询助手
node.js·agent·网站开发·智能体·wwwoop.com
幸运小圣2 天前
fs 模块完全指南:文件读写、移动删除与文件夹操作(新手友好)【Node.js】
node.js·编辑器·vim
Dumbness2 天前
不发 npm 也能 npx:用 github: 协议分发一个零依赖 CLI
node.js
Patrick_Wilson3 天前
npm 的 bin 如何接到 npm run 与 npx
npm·node.js·前端工程化