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

相关推荐
踏着七彩祥云的小丑4 小时前
pytest——Mark标记
开发语言·python·pytest
Dream of maid4 小时前
Python12(网络编程)
开发语言·网络·php
W23035765735 小时前
经典算法:最长上升子序列(LIS)深度解析 C++ 实现
开发语言·c++·算法
Y4090015 小时前
【多线程】线程安全(1)
java·开发语言·jvm
不爱吃炸鸡柳5 小时前
Python入门第一课:零基础认识Python + 环境搭建 + 基础语法精讲
开发语言·python
minji...6 小时前
Linux 线程同步与互斥(三) 生产者消费者模型,基于阻塞队列的生产者消费者模型的代码实现
linux·运维·服务器·开发语言·网络·c++·算法
Dxy12393102166 小时前
Python基于BERT的上下文纠错详解
开发语言·python·bert
wjs20248 小时前
JavaScript 语句
开发语言
cmpxr_9 小时前
【C】局部变量和全局变量及同名情况
c语言·开发语言