node.js学习笔记 (新版url模块)

1.通过新版url模块解决路由后面带参数的问题

有时候路由会带参数什么的     以下就是这个问题

 

这时候则通过新版url模块来解决

//引入模块
const http = require('http')
const serve = http.createServer()

serve.on('request', (req, res) => {
    //赋值  方便之后写代码
    const newVersion =new URL(req.url,'http://localhost:3000')
    const pathUrl=newVersion.pathname
    //输出   可以看看里面是什么
    console.log(pathUrl)
    //错误提示
    let content = '<h1>404 not found</h1>'

    if (pathUrl == '/' || pathUrl == "/index") {
        content = '<h1>这是首页</h1>'
    }
    if (pathUrl == '/favicon.ico' ) {
       return
    }
    if (pathUrl == '/about') {
        content = '<h1>这是关于页面</h1>'
    }
    //请求头  以utf-8解析模板
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    //结束  并在里面返回模板
    res.end(content)
})
    
    //设置服务器地址
serve.listen('3000', () => {
    console.log('http://localhost:3000')
})

2.通过新版url获取前端传的参数

 

serve.on('request', (req, res) => {
    //赋值  方便之后写代码
    const newVersion =new URL(req.url,'http://localhost:3000')
    //拿到处理过的路径
    const pathUrl=newVersion.pathname
    //循环newVersion.searchParams
    for(let [key,value] of newVersion.searchParams){
        //输出拿到的值
        console.log(key,value)
    }
    //错误提示
    let content = '<h1>404 not found</h1>'

    if (pathUrl == '/' || pathUrl == "/index") {
        content = '<h1>这是首页</h1>'
    }
    if (pathUrl == '/favicon.ico' ) {
       return
    }
    if (pathUrl == '/about') {
        content = '<h1>这是关于页面</h1>'
    }
    //请求头  以utf-8解析模板
    res.setHeader('Content-Type', 'text/html;charset=utf-8')
    //结束  并在里面返回模板
    res.end(content)
})
    
    //设置服务器地址
serve.listen('3000', () => {
     console.log('http://localhost:3000')
})

基本上跟第一步没什么区别   以下就是多出来的代码

  const newVersion =new URL(req.url,'http://localhost:3000')
  for(let [key,value] of newVersion.searchParams){
        console.log(key,value)
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值