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

相关推荐
Chester_199941 分钟前
CSP202203C.计算资源调度器
开发语言·数据结构·c++·蓝桥杯
EXI-小洲2 小时前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
会周易的程序员2 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
机器视觉知识推荐、就业指导2 小时前
为什么老说“纯 Qt 没啥就业市场”?
开发语言·qt
telepan2 小时前
Qt 开发避坑与性能指南:如何优雅、安全地定义全局常量字符串?
开发语言·qt
m0_695251493 小时前
Qt MaintenanceTool 使用国内镜像加速下载(超详细教程)
开发语言·qt
大衛說4 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习
可乐鸡翅yeah_5 小时前
hls.js 内存泄漏实战排查,直播 M3U8 长时间播放异常定位方案
开发语言·javascript·python·django·ecmascript·m3u8·m3u8在线
2601_962203515 小时前
Java进阶07集合(续)
java·开发语言
郑州光合科技余经理6 小时前
本地生活服务系统:模块边界与结算字段怎么拆
java·开发语言·前端·后端·系统架构·uni-app·php