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 的版本吗?那个更接近实际开发。

相关推荐
黄贵根2 小时前
JavaScript实现教培行业意向登记系统
开发语言·javascript·ecmascript
zzzll11115 小时前
Claude Code离线安装方案揭秘
开发语言·php
wling03016 小时前
vasp虚频计算-python脚本
开发语言·windows·python·vasp计算
郝学胜-神的一滴6 小时前
Qt 高级编程 040:按钮悬浮弹出滑块弹窗的完整攻略
开发语言·c++·qt·软件工程·用户界面
xrandzj7 小时前
Python面向对象编程入门:类、实例、初始化与封装实践
开发语言·python
DLYSB_7 小时前
API 网关流量洪峰与突发 CC 攻击:我用 Go 写了个“现场物理防御哨兵”,把故障响应压缩到秒级
开发语言·后端·golang·报警灯
雨田言炎9 小时前
四、关于Qt项目需要知道的
开发语言·笔记·qt
程序喵大人10 小时前
【C++进阶】STL算法与函数对象 - 02 sort为什么需要随机访问迭代器
开发语言·c++·算法
SomeB1oody10 小时前
【RustyML入门】2.6. 线性判别分析
开发语言·后端·机器学习·rust·教程
用户昵称10011 小时前
C/C++编程-工程实践-本地存储log的工程意义
c语言·开发语言