005Node.js模块URL的使用

引入 URL 模块

要使用 URL 模块,首先需要在代码中引入它。可以使用以下代码将 URL 模块导入到你的脚本中:

javascript 复制代码
const url = require('url');

实例代码

javascript 复制代码
const url=require('url');
var api='http://www.baidu.com?name=shixiaobin&age=20';
console.log(url.parse(api));
console.log(url.parse(api,true));

var getValue=url.parse(api,true).query;

console.log(getValue);

//两种方法都能完成显示
console.log(`姓名:${getValue.name}--年龄:${getValue.age}`);  //引号是TAB上面的',不是普通的引号
console.log('姓名:'+getValue.name+'--年龄:'+getValue.age);

http://127.0.0.1:3000/?name=shixiaobin\&age=20 想获取url传过来的name和age

javascript 复制代码
//引入http模块
const http=require('http');
//引入url模块
const url=require('url');

//http.createServer((req,res)=>{
http.createServer(function (req,res) {

    //req 获取客户端传过来的信息
    //res 给浏览器响应信息
    //http://127.0.0.1:3000/?name=shixiaobin&age=20 想获取url传过来的name和age
    //设置响应头
    //状态码是200,文件类型是html,字符集是utf-8
    res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"});  //解决乱码
    res.write("<head><meta charset='UTF-8'></head>");  //如果没有这一行,下面的 "你好" 是乱码 //解决乱码
  
    //console.log(req);//获取好多信息
    console.log(req.url);//获取url

    if(req.url!='/favicon.ico'){
      var userinfo=url.parse(req.url,true).query;
      console.log(`姓名:${userinfo.name}--年龄:${userinfo.age}`);
    }

    res.end();//结束响应,如果没有这一行,浏览器左上角的图标一直在转圈
}).listen(3000);  //端口建议3000以上,防止冲突


相关推荐
烟雨空灵14 小时前
25 天做了个独立开发者作品橱窗,收录 340+ 件作品,代码全开源
前端·node.js
用户2160763408316 小时前
1200 个任务里,97 个还开着,0 个我能做
node.js
不要试图纠正别人1 天前
1055 个文件,共享 0 字节:pnpm 硬链接的静默降级
前端·node.js
吴名氏.2 天前
从零手写一个 AI Agent 框架(TypeScript 完整实现):Function Calling 循环、流式输出与错误恢复
人工智能·typescript·node.js·大模型·ai agent·functioncalling·llm 应用开发
关键词安全3 天前
PHP / Node.js / Go / Rust 全部中招(CVE-2026-109618、109619、111497、111943)完整排查与修复清单
golang·rust·node.js
zhensherlock4 天前
Protocol Launcher 系列:CodeHub 移动端 GitHub 协作利器
前端·javascript·typescript·node.js·自动化·github·js
jaysee-sjc4 天前
【黑马点评】Day02:优惠券秒杀与分布式锁
java·分布式·nginx·spring·node.js·tomcat·maven
ZhengEnCi5 天前
Express 企业级项目结构怎么组织:五层骨架、单向依赖和一份能跑的边界检查脚本
javascript·node.js·express
Dumbness5 天前
搜 platform 却给出 Form 表单:离线文档检索把短关键词当成了子串
javascript·node.js
用户216076340836 天前
一个 2 MB 的 .zst 文件,解压出来只有十几 KB
node.js