node.js 内置模块 http 和 url

旧的HTTP和URL内置模块的一些方法

// 引入http和url内置模块
import http from 'http'
import url from 'url'
import { name } from './renderHTML.js'
import {status} from './renderStatus.js'

// 创建服务器
// req 接收浏览器传的参数
// res 返回给浏览器的内容
http.createServer((req, res) => {
  // /favicon.ico是本地默认加载的网站小图标(下方代码直接跳过打印/favicon.ico)
  if (req.url === "/favicon.ico") {
    return
  }

  // url.parse(req.url).pathname 表示只接收路径
  var pathname = url.parse(req.url).pathname
  console.log(pathname)
  
  // 把浏览器传的参数转成json格式
  var val = url.parse(req.url, true)
  console.log(val) //取参数用val.query.参数名

  // 把json字符串转回路径格式
  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)
  //https://www.baidu.com:443/ad/index.html?id=8&name=mouse#tag=110

  // res.writeHead 设置请求头(状态,{参数})
  // res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
  res.writeHead(status(pathname))

  // res.write 往浏览器写入
  res.write(name(pathname))

  // res.end() 结束语句
  res.end()

}).listen(3000, () => {
  console.log("server start")
})

 新的HTTP和URL内置模块的一些方法

const myURL = new URL('/foo', 'https://example.org/');
// https://example.org/foo

// myUrl.searchParams 代表url的参数

//可以用迭代器来取参数值
for (var [key, value] of myUrl.searchParams) {
   console.log(key,value);
}

//format 对序列化的网址自定义输出路径的格式

auth <boolean> 如果字符串应包含用户名和密码,则为 true,否则为 false。 默认值: true。
fragment <boolean> 如果字符串应包含片段,则为 true,否则为 false。 默认值: true。
search <boolean> 如果字符串应包含搜索查询,则为 true,否则为 false。 默认值: true。
unicode <boolean> true 如果字符串的主机组件中的 Unicode 字符应该被直接编码而不是 Punycode 编码。 默认值: false。

import url from 'url';

const myURL = new URL('https://a:b@測試?abc#foo');

console.log(url.format(myURL, { fragment: false, unicode: true, auth: false }));
// 打印 'https://測試/?abc'

//此函数可确保正确解码百分比编码字符,并确保跨平台有效的绝对路径字符串。
url.fileURLToPath(url)

console.log(new URL('file:///C:/path/').pathname) //  /C:/path/  错误
console.log(fileURLToPath('file:///C:/path/') )   //  C:\path\   正确

以上url方法只是一部分,可以查看官方文档,里面有更多可用的方法。 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微光无限

破晓的日子还有很多!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值