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

相关推荐
不会写DN2 小时前
[特殊字符] JS Date 对象8大使用场景
开发语言·前端·javascript
蓝天星空2 小时前
java、python、C# 编程语言的区别,不同开发语言平台对比有什么优势和缺点
java·开发语言·python
for_ever_love__2 小时前
Objective-C学习: OC方法调用的本质
开发语言·学习·ios·objective-c
Monkey-旭2 小时前
Java HTTP证书全用法详解:原理、配置、实战与问题排查
java·开发语言·http·证书·ssl
m0_730115112 小时前
C++与Python混合编程实战
开发语言·c++·算法
LSL666_2 小时前
IService——删除
java·开发语言·mybatisplus·iservice
小罗和阿泽3 小时前
接口测试系列 接口自动化测试 pytest框架(三)
开发语言·python·pytest
毕设源码-邱学长9 小时前
【开题答辩全过程】以 基于Java的学校住宿管理系统的设计与实现为例,包含答辩的问题和答案
java·开发语言
rookieﻬ°10 小时前
PHP框架漏洞
开发语言·php