Node.js怎么搭建HTTP服务器

在 Node.js 中搭建一个简单的 HTTP 服务器非常容易。以下是一个基本的示例,演示如何使用 Node.js 创建一个简单的 HTTP 服务器:

// 导入 http 模块 const http = require('http');

// 创建一个 HTTP 服务器

const server = http.createServer((req, res) => {

// 设置响应头

res.writeHead(200, {'Content-Type': 'text/plain'});

// 发送响应内容

res.end('Hello, World!\n');

});

// 监听特定端口

const port = 3000;

server.listen(port, () => {

console.log(`Server is running on http://localhost:${port}`);

});

在这个示例中,我们使用 Node.js 的 http 模块来创建一个 HTTP 服务器。createServer 方法接受一个回调函数,这个回调函数会在每次有请求时被调用。在回调函数中,我们可以设置响应头、发送响应内容,并使用 res.end() 结束响应。

然后,我们使用 listen 方法来指定服务器监听的端口。在这个例子中,服务器会在端口 3000 上监听。当服务器启动后,你可以在浏览器中访问 http://localhost:3000,应该会看到 "Hello, World!"。

相关推荐
codingWhat17 小时前
能效平台设计方案(打通gitlab和飞书)
后端·node.js·koa
喵个咪2 天前
Go-Wind HTTP 服务器从入门到精通
后端·http·go
见过夏天2 天前
Node.js 常用命令全攻略
node.js
前端双越老师3 天前
我从 0 开发的 AI Agent 智语项目发布了
前端·node.js·agent
kyriewen3 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
donecoding4 天前
3 条命令搞定闭环 Monorepo:Lerna 版本管理 + 拓扑构建 + 自定义分发
前端·前端框架·node.js
Flynt5 天前
npm v12 来了:allowScripts 默认关闭,我的项目差点跑不起来
安全·npm·node.js
叫我Paul就好6 天前
尝试 Node 搭建后端-开发框架
node.js
Goodbye7 天前
大模型无状态架构:从 HTTP 协议到 Harness AI 工程的深度解析
http
风止何安啊7 天前
网课倍速痛点解决:一套前端代码实现自由控速播放器
前端·javascript·node.js