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

相关推荐
惊鸿一博1 天前
统计_滚动标准差:局部波动性衡量
开发语言·python
这个DBA有点耶1 天前
数据库管理工具+开发工具的融合:AI如何重塑DBA工作流?
开发语言·数据库·人工智能·sql·云计算·dba
lynnlovemin1 天前
【信息学竞赛专题】滑动窗口(尺取法)超全详解|C++模板+经典例题+避坑指南
开发语言·c++·算法·滑动窗口·信息学竞赛
wjs20241 天前
JavaScript 类型转换
开发语言
似水এ᭄往昔1 天前
【Qt】--Qt概述
开发语言·c++·qt
星秀日1 天前
rust学习入门
开发语言·学习·rust
星越华夏1 天前
python办公自动化,csv文件/excel文件差集合并
开发语言·python·excel
弹简特1 天前
【零基础学Python】04-Python运算符、分支、循环与随机数实战教程
开发语言·python
不会C语言的男孩1 天前
C++ Primer Plus 第3章:处理数据
开发语言·c++
一天 24h1 天前
Python自定义迭代器:从入门到精通
开发语言·python·迭代器模式·学习方法·新人首发