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!"。

相关推荐
酱学编程12 小时前
【从零到一实现一个 AI Agent 框架 · 第四篇】04. 任务规划:拆解复杂目标 -
服务器·网络·数据库·人工智能
艾莉丝努力练剑14 小时前
OpenCode AI 编程:Ubuntu 24.04 环境安装与使用指南
linux·服务器·网络·人工智能·tcp/ip·ubuntu
崇山峻岭之间14 小时前
Keil5输出hex转换为bin的设置
linux·运维·服务器
Tian_Hang15 小时前
Eclipse Ditto 的权限策略
java·服务器·前端·网络·ide·ubuntu·eclipse
冰暮流星16 小时前
flask之http请求方法
网络·网络协议·http
着迷不白17 小时前
Linux 磁盘管理完全指南:分区、文件系统、挂载与 LVM 实战
linux·运维·服务器
山川而川-R17 小时前
LangChain
linux·运维·服务器
QH_ShareHub17 小时前
Linux 根目录结构详解
linux·运维·服务器
骑士雄师17 小时前
langchain:推荐切片策略
服务器·前端·langchain
千逐6818 小时前
Uniapp 鸿蒙实战之 AtomGit APP - 仓库详情与文件树浏览
服务器·microsoft·uni-app