nodJS写全面httpserver程序
以下是一个基本的 Node.js HTTP 服务器程序:
const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
这个程序创建了一个 HTTP 服务器,监听 127.0.0.1:3000 地址。当访问该地址时,服务器会返回一个 "Hello, World!" 的文本。
以下是一个稍微复杂一些的程序,可以处理静态文件和动态路由:
const http = require('http');
const fs = require('fs');
const path = require('path');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
const parsedUrl = url.parse(req.url);
const pathname = parsedUrl.pathname;
const ext = path.parse(pathname).ext;
if (ext) {
const filePath = path.join(__dirname, 'public', pathname);
fs.readFile(filePath, (err, data) => {
if (err) {
res.statusCode = 404;
res.end(`File not found: ${pathname}`);
} else {
res.statusCode = 200;
res.setHeader('Content-Type', getContentType(ext));
res.end(data);
}
});
} else {
switch (pathname) {
case '/':
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(`
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
`);
break;
case '/about':
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('This is the about page');
break;
default:
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Page not found');
break;
}
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
function getContentType(ext) {
switch (ext) {
case '.html':
return 'text/html';
case '.css':
return 'text/css';
case '.js':
return 'text/javascript';
case '.png':
return 'image/png';
case '.jpg':
return 'image/jpeg';
default:
return 'application/octet-stream';
}
}
这个程序先根据请求的 URL 解析出请求的路径,然后通过路径的后缀名判断请求的是静态文件还是动态路由。如果是静态文件,就读取文件内容并返回。如果是动态路由,就根据路径返回不同的内容。同时,根据后缀名设置 Content-Type 响应头。
原文地址: https://www.cveoy.top/t/topic/5VB 著作权归作者所有。请勿转载和采集!