使用Node.js内置http模块可快速创建Web服务器,通过createServer处理请求响应,监听端口并根据URL实现简单路由,返回文本或HTML内容。

Node.js 是基于 Chrome V8 引擎的 JavaScript 运行环境,它让 JavaScript 可以在浏览器之外运行。利用 Node.js 的内置模块 http,我们可以快速搭建一个基础的 Web 服务器。
Node.js 提供了 http 模块,用于创建服务器并监听客户端请求。以下是一个最简单的 Web 服务器示例:
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, 这是一个简单的 Node.js 服务器!\n');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`服务器正在运行,访问 http://localhost:${PORT}`);
});
说明:
如果想返回网页内容,只需更改响应头中的 Content-Type,并发送 HTML 字符串:
立即学习“Java免费学习笔记(深入)”;
const http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(`
<h1>欢迎来到我的网站</h1>
<p>这是用 Node.js 搭建的简单页面</p>
`);
});
server.listen(3000, () => {
console.log('服务器已启动,端口 3000');
});
注意将 Content-Type 改为 text/html,并可加入 utf-8 编码支持中文显示。
可以通过判断 req.url 实现简单的路由功能:
const http = require('http');
const server = http.createServer((req, res) => {
const { url } = req;
if (url === '/' || url === '/home') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>首页</h1>');
} else if (url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>关于页面</h1>');
} else {
res.writeHead(404, { 'Content-Type': "text/html" });
res.end('<h1>页面未找到</h1>');
}
});
server.listen(3000, () => {
console.log('服务器运行中:http://localhost:3000');
});
这样可以根据用户访问的 URL 返回不同的响应内容,模拟基本的页面跳转。
将代码保存为 server.js,然后在终端执行:
node server.js
打开浏览器访问 http://localhost:3000 即可看到输出内容。
确保已安装 Node.js,可通过命令检查版本:
node -v
以上就是使用JavaScript实现一个简单的Web服务器_Node.js的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号