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

相关推荐
执笔论英雄20 小时前
【RL]expand_requests干啥的
服务器·开发语言·python
Zeku20 小时前
20251125 - 为什么Linux是非实时操作系统?
linux·服务器
前端fighter20 小时前
全栈项目:校友论坛系统
vue.js·mongodb·node.js
2***c43520 小时前
nginx服务器实现上传文件功能_使用nginx-upload-module模块
服务器·前端·nginx
k***858420 小时前
Nginx中$http_host、$host、$proxy_host的区别
运维·nginx·http
kyle~20 小时前
数据结构---堆(Heap)
服务器·开发语言·数据结构·c++
虾..20 小时前
Linux 进程控制
linux·运维·服务器
last demo20 小时前
pxe自动化安装系统实验
linux·运维·服务器·自动化
实心儿儿21 小时前
Linux —— 基础开发工具2
linux·运维·服务器
源梦想21 小时前
英雄无敌动作冒险网页小游戏Linux部署演示
linux·运维·服务器