Node.js的http服务

Node.js 的 HTTP 服务是用来创建 Web 服务器的核心模块,不需要安装任何第三方库,直接内置在 Node.js 里。

最基础的 HTTP 服务:

const http = require('http');

const server = http.createServer((req, res) => {

res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });

res.end('Hello World!');

});

server.listen(3000, () => {

console.log('服务器运行在 http://localhost:3000');

});

浏览器访问 http://localhost:3000 就能看到 "Hello World!"

TypeScript 版本(对应 Day16):

import http, { IncomingMessage, ServerResponse } from 'http';

const server = http.createServer((req: IncomingMessage, res: ServerResponse) => {

// 获取请求路径和方法

const { url, method } = req;

// 简单路由

if (url === '/' && method === 'GET') {

res.writeHead(200, { 'Content-Type': 'application/json' });

res.end(JSON.stringify({ message: '首页', code: 200 }));

} else if (url === '/api/users' && method === 'GET') {

res.writeHead(200, { 'Content-Type': 'application/json' });

res.end(JSON.stringify({ users: 'Tony', 'Alice' }));

} else {

res.writeHead(404, { 'Content-Type': 'application/json' });

res.end(JSON.stringify({ message: '页面不存在', code: 404 }));

}

});

server.listen(3000, () => {

console.log('服务器运行在 http://localhost:3000');

});

核心概念:

概念 说明

req 请求对象,包含 url、method、headers、body

res 响应对象,用来返回数据

res.writeHead() 设置状态码和响应头

res.end() 结束响应,返回数据

server.listen() 监听端口,启动服务

实际开发中:

原生 http 模块比较底层,实际项目一般用框架封装:

• Express - 最流行,简单易用

• Fastify - 性能更好

• Koa - 更现代,async/await 友好

• NestJS - 企业级,TypeScript 原生支持

想看 Express + TypeScript 的版本吗?那个更接近实际开发。

相关推荐
Sarvartha1 小时前
Object 类
java·开发语言
j7~1 小时前
【C++ 标准项目】发布订阅消息队列 (篇七):项目创建与基础工具模块搭建
开发语言·c++·log4j·uuid·protobuf·helper工具·消息定义类型和交换机类型定义
leisoo80971 小时前
股票筹码分布怎么用获利比例成本区间与集中度实战 IG50免费开源股票数据API接口
开发语言·jvm·数据库·python·开源
Lazionr2 小时前
unordered_map和unordered_set的使用
开发语言·c++·算法
Xiu Yan2 小时前
Python 数据分析:数据分析步骤
开发语言·python·数据分析
黑妹天下第一乖2 小时前
小智改造实战解读-用kokoro-onnx替换云端 TTS 的完整记录
大数据·开发语言·人工智能·python·交互
郑州光合科技余经理2 小时前
本地生活平台搭建:跨业态用户标识怎么贯通
java·开发语言·前端·后端·uni-app·php·ai编程
深盾科技_Virbox2 小时前
云端与本地并行交付,软件许可管理如何实现统一运营?
java·大数据·开发语言·安全
xuxigifxfh3 小时前
HJ15 求int型正整数在内存中存储时1的个数
java·开发语言·华为机考
Wokoo73 小时前
自动化测试入门:核心场景、回归测试与 Web 自动化环境搭建
java·开发语言·测试工具