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以上,防止冲突


相关推荐
hoLzwEge2 天前
pnpm vs npm:新一代包管理器的范式革命
前端框架·node.js
麻辣凉茶2 天前
给阿嬤一封来自云端的信(上)
前端·node.js
codingWhat3 天前
能效平台设计方案(打通gitlab和飞书)
后端·node.js·koa
见过夏天5 天前
Node.js 常用命令全攻略
node.js
前端双越老师5 天前
我从 0 开发的 AI Agent 智语项目发布了
前端·node.js·agent
kyriewen6 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
donecoding6 天前
3 条命令搞定闭环 Monorepo:Lerna 版本管理 + 拓扑构建 + 自定义分发
前端·前端框架·node.js
Flynt7 天前
npm v12 来了:allowScripts 默认关闭,我的项目差点跑不起来
安全·npm·node.js
叫我Paul就好8 天前
尝试 Node 搭建后端-开发框架
node.js
风止何安啊10 天前
网课倍速痛点解决:一套前端代码实现自由控速播放器
前端·javascript·node.js