在 Node.js 中创建 HTTP 服务器是一个基本且重要的任务。Node.js 提供了 http 模块,用于构建能够处理 HTTP 请求和响应的服务器。在这篇文章中,我们将通过几个例子来展示如何使用 Node.js 创建 HTTP 服务器。
下面是一个简单的 HTTP 服务器,它监听 8080 端口,并对所有请求响应 "Hello, World!"。
JavaScriptconst http = require('http');
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
server.listen(8080, () => {
console.log('Server running at http://127.0.0.1:8080/');
});

这个例子演示了如何根据不同的 HTTP 方法(GET, POST, etc.)来处理请求。
JavaScriptconst http = require('http');
const server = http.createServer((req, res) => {
if (req.method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Received a GET request\n');
} else if (req.method === 'POST') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Received a POST request\n');
} else {
res.writeHead(405, { 'Content-Type': 'text/plain' });
res.end(`${req.method} is not allowed on the server\n`);
}
});
server.listen(8080, () => {
console.log('Server running at http://127.0.0.1:8080/');
});

在这个例子中,我们将解析请求的 URL 来提供不同的响应。
JavaScriptconst http = require("http");
const url = require("url");
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
// 默认返回的内容
let content = "Page not found\n";
let statusCode = 404;
// 处理不同的路由
if (req.method === "GET") {
res.setHeader("Content-Type", "text/html"); // 预先设置内容类型
if (parsedUrl.pathname === "/") {
content = "<h1>Home</h1>";
statusCode = 200;
} else if (parsedUrl.pathname === "/about") {
content = "<h1>About</h1>";
statusCode = 200;
}
} else if (req.method === "POST" && parsedUrl.pathname === "/submit") {
let body = '';
req.on('data', chunk => {
body += chunk.toString();
});
req.on('end', () => {
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(`Data:${body}\n`);
});
return; // 防止后续设置响应头
}
// 如果请求不是POST到/submit,写入头部并且结束响应
res.writeHead(statusCode);
res.end(content);
});
server.listen(8080, () => {
console.log("服务器运行在 http://127.0.0.1:8080/");
});

此例演示如何处理 URL 中的查询字符串参数。
JavaScriptconst http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url, true);
const query = parsedUrl.query;
res.writeHead(200, { 'Content-Type': 'text/plain' });
if (query.name) {
res.end(`Hello, ${query.name}!\n`);
} else {
res.end('Hello, Stranger!\n');
}
});
server.listen(8080, () => {
console.log('Server running at http://127.0.0.1:8080/');
});
HTMLhttp://127.0.0.1:8080/?name=123

这个例子创建了一个简单的静态文件服务器,可以用来提供 HTML, CSS 和 JavaScript 文件。
JavaScriptconst http = require('http'); // 引入HTTP模块
const fs = require('fs'); // 引入文件系统模块
const path = require('path'); // 引入路径模块
// 创建HTTP服务器
const server = http.createServer((req, res) => {
// 解析请求的文件路径,如果请求根路径,则返回index.html
let filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url);
// 获取文件的扩展名
let extname = path.extname(filePath);
// 默认内容类型为text/html
let contentType = 'text/html';
// 根据文件扩展名设置正确的内容类型
switch (extname) {
case '.css':
contentType = 'text/css';
break;
case '.js':
contentType = 'text/javascript';
break;
case '.json':
contentType = 'application/json';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
// 可以根据需要添加更多的内容类型
}
// 读取指定的文件
fs.readFile(filePath, (error, content) => {
if (error) {
// 如果未找到文件,返回404页面
if (error.code === 'ENOENT') {
fs.readFile(path.join(__dirname, 'public', '404.html'), (error, content) => {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end(content, 'utf-8');
});
} else {
// 处理其他错误,如服务器错误
res.writeHead(500);
res.end(`抱歉,检查站点管理员的错误: ${error.code} ..\n`);
}
} else {
// 成功读取文件,返回文件内容
res.writeHead(200, { 'Content-Type': contentType });
res.end(content, 'utf-8');
}
});
});
// 服务器监听端口 8080
server.listen(8080, () => {
console.log('服务器运行在 http://127.0.0.1:8080/');
});
创建public文件夹,再目录下 创建文件index.html
HTML<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>hello world</h1>
</body>
</html>
在以上的例子中,我们创建了一个基本的静态文件服务器,它会根据请求的文件类型设置正确的 Content-Type 并提供文件内容。如果请求的文件不存在,它会返回一个 404 错误页面。
通过这些例子,你应该能够开始构建自己的 HTTP 服务器,并根据自己的需求进行扩展和定制。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!