nodejs中http模块搭建web服务器

先看一下常见教程的写法,他们一般都是采用传入回调函数作为方法参数的写法,其实本质也是用的事件回调,这种方式也只适合简单的场景,下面看代码:

javascript 复制代码
const http = require('http')

const hostname = '127.0.0.1'
const port = 3000

// 通过createServer来创建一个服务对象
const server = http.createServer((req,res) => {
    res.end('Hello World!!!')
})

// 服务对象监听特定的端口,也就是启动这个服务器
server.listen(port, hostname, () => {
    console.log('服务已启动...');
    
})

在看一下通过事件事件回调的方式来创建web服务器:一般都是先注册好所有可能的事件以及对应的回调,最后在调用listen()方法启动服务器

javascript 复制代码
const http = require('http')

const hostname = '127.0.0.1'
const port = 3000

// 通过createServer来创建一个服务对象
const server = http.createServer()
server.on('request', (req,res) => {
    res.end('Hello World!!!')
})

server.on('listening', () => {
    console.log('服务已启动...');
})

// 服务对象监听特定的端口,也就是启动这个服务器
server.listen(port, hostname)
相关推荐
晚风吹长发9 分钟前
Docker使用——Docker容器及相关命令
linux·运维·服务器·docker·容器·架构
Kina_C1 小时前
Apache HTTP Server 安装、配置与高级功能详解
linux·http·apache
吃糖的小孩1 小时前
从只读页面到可控真实探针:我如何给 Owner Console 加手动诊断
前端
谷无姜1 小时前
为什么你的性能优化无效?可能是"木桶效应"在作祟
前端·性能优化
雾非雾1 小时前
《基于具身交互智能数字人技术:如何打造AI数字人宣讲平台"红厅智播”》
前端
jun_bai1 小时前
Orthanc服务器使用java上传dicom影像文件
java·运维·服务器
Revolution611 小时前
一段 JavaScript 代码执行时,到底发生了什么
前端·javascript
智能起源1 小时前
关于元素层级过多,导致压祯的问题(使用winform或者WPF应用的webview组件嵌套网页时,动效卡顿问题)
前端
RisunJan2 小时前
Linux命令-semanage(SELinux 策略管理)
linux·运维·服务器