当前位置: 首页 > news >正文

【Node】【7】函数

函数可以作为变量传递

function execute(someFunction, value) {someFunction(value);
}execute(function(word){ console.log(word) }, "Hello");

函数传递让http服务器工作,向createServer 传递了一个回调函数,该回调函数会在每次接收到 HTTP 请求时被调用,并且该回调函数会接收两个参数:requestresponse,分别代表请求和响应对象。具体来说,createServer 方法的入参是一个用于处理请求的回调函数。

var http = require("http");// 定义 onRequest 函数,用于处理 HTTP 请求
function onRequest(request, response) {response.writeHead(200, { "Content-Type": "text/plain" });response.write("Hello World");response.end();
}// 创建一个 HTTP 服务器实例,请求处理函数为onRequest
http.createServer(onRequest).listen(8888);

运行这段代码后,Node.js 服务器会在本地的 8888 端口启动。

当有请求发送到该端口时,服务器会调用 onRequest 函数来处理请求,并返回 “Hello World” 给请求方。

您可以打开一个浏览器并访问 http://localhost:8888/,这样浏览器就会发送一个 GET 请求到您的 Node.js 服务器。服务器会接收这个http请求,从而执行onRequest回调函数,并返回 “Hello World” 给浏览器,在浏览器中显示 “Hello World”。

在这里插入图片描述

要在 Node.js 服务器中处理不同的路由请求,您可以根据请求的 URL 路径来区分不同的路由,并执行相应的处理逻辑。以下是一个简单示例,演示如何在 Node.js 服务器中处理不同的路由请求:

const http = require('http');function onRequest(request, response) {const { url } = request;if (url === '/') { response.writeHead(200, { "Content-Type": "text/plain" });response.write("Hello World");response.end();} else if (url === '/about') {response.writeHead(200, { "Content-Type": "text/plain" });response.write("About Us Page");response.end();} else {response.writeHead(404, { "Content-Type": "text/plain" });response.write("Page Not Found");response.end();}
}const server = http.createServer(onRequest);server.listen(3000, 'localhost', () => {console.log('Server is running at http://localhost:3000/');
});

在上述示例中:

  • 当用户访问根路径 / 时,服务器返回 “Hello World”。
  • 当用户访问 /about 路径时,服务器返回 “About Us Page”。
  • 对于其他路径,服务器返回 404 Not Found。

在这里插入图片描述

上述的例子都是通过在浏览器输入请求路径,触发回调函数,写死的response。

下面给个示例:演示了如何创建一个服务器,然后在服务器端代码中发起一条 GET 请求

const http = require('http');const onRequest = (req, res) => {// 发起 GET 请求http.get('http://www.example.com', (response) => {let data = '';// 接收到数据将数据保存response.on('data', (chunk) => {data += chunk;});// 结束后写到res里作为服务器的返回。response.on('end', () => {res.writeHead(200, { 'Content-Type': 'text/plain' });res.write('Received response from http://www.example.com: ' + data);res.end();});}).on('error', (err) => {console.error('Error during GET request:', err);res.writeHead(500, { 'Content-Type': 'text/plain' });res.write('Error during GET request');res.end();});
}// 创建 HTTP 服务器,发起请求是调用onRequest回调函数
const server = http.createServer(onRequest);// 启动服务器
server.listen(3000, 'localhost', () => {console.log('Server is running at http://localhost:3000/');
});

node 获取到post请求,想要看post请求里的body

//router.js
exports.route = function(pathname) {console.log("About to route a request for " + pathname);
}
//server.js
var http = require("http");
var url = require("url");function start(route) {function onRequest(request, response) {var pathname = url.parse(request.url).pathname;console.log("Request for " + pathname + " received.");console.log("type=", request.method);route(pathname);if (request.method === "POST") {let body = "";request.on("data", (chunk) => {body += chunk.toString(); // 将数据块转换为字符串});request.on("end", () => {console.log("POST 请求的请求体:", body);response.writeHead(200, { "Content-Type": "text/plain" });response.end("Received POST data");});} else {response.writeHead(200, { "Content-Type": "text/plain" });response.write("Hello World");response.end();}}http.createServer(onRequest).listen(8888);console.log("Server has started.");
}exports.start = start;
// index.js
var router = require('./router')
var server = require('./server')
server.start(router.route)

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 8.28-回顾+容器与主机之间的通信+跨主机容器之间的通信
  • NTP简介及相关概念
  • mysql创建存储过程
  • 音频PCM的能量dB计算
  • iOS巨魔商店免越狱作弊解决方案
  • Redis: 用于纯缓存模式需要注意的地方
  • zoom 会议 javascript 转录例子
  • Unity 贴图拷贝与性能对比
  • Python中的`while`循环:探索无限可能
  • 《深入理解 C++虚函数:开启多态之门的关键》
  • 双登集团IPO:铅酸电池业务仍为重心,暴露了成长天花板?
  • AD7606芯片驱动-FPGA实现
  • 打卡50天------图论
  • 【给女朋友讲C++】C++的调试之gdb
  • python socket 发生UDP 和 UDPServer接受UDP实例
  • @angular/forms 源码解析之双向绑定
  • [数据结构]链表的实现在PHP中
  • css系列之关于字体的事
  • IndexedDB
  • JDK 6和JDK 7中的substring()方法
  • js对象的深浅拷贝
  • React+TypeScript入门
  • React16时代,该用什么姿势写 React ?
  • TiDB 源码阅读系列文章(十)Chunk 和执行框架简介
  • use Google search engine
  • vue 个人积累(使用工具,组件)
  • Vue2.x学习三:事件处理生命周期钩子
  • 大主子表关联的性能优化方法
  • 关于Android中设置闹钟的相对比较完善的解决方案
  • 码农张的Bug人生 - 见面之礼
  • 前端学习笔记之原型——一张图说明`prototype`和`__proto__`的区别
  • 浅谈web中前端模板引擎的使用
  • 手写双向链表LinkedList的几个常用功能
  • 说说动画卡顿的解决方案
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • 网页视频流m3u8/ts视频下载
  • 学习Vue.js的五个小例子
  • 一个普通的 5 年iOS开发者的自我总结,以及5年开发经历和感想!
  • Unity3D - 异步加载游戏场景与异步加载游戏资源进度条 ...
  • ​Z时代时尚SUV新宠:起亚赛图斯值不值得年轻人买?
  • ​人工智能之父图灵诞辰纪念日,一起来看最受读者欢迎的AI技术好书
  • #每日一题合集#牛客JZ23-JZ33
  • #我与Java虚拟机的故事#连载04:一本让自己没面子的书
  • (pytorch进阶之路)CLIP模型 实现图像多模态检索任务
  • (分类)KNN算法- 参数调优
  • (免费分享)基于springboot,vue疗养中心管理系统
  • (南京观海微电子)——I3C协议介绍
  • (一)、软硬件全开源智能手表,与手机互联,标配多表盘,功能丰富(ZSWatch-Zephyr)
  • (一)基于IDEA的JAVA基础10
  • (原+转)Ubuntu16.04软件中心闪退及wifi消失
  • (转)IOS中获取各种文件的目录路径的方法
  • (转)程序员疫苗:代码注入
  • .Net Core中的内存缓存实现——Redis及MemoryCache(2个可选)方案的实现
  • .net framework 4.8 开发windows系统服务
  • .NET MVC第三章、三种传值方式