NodeJs 第十七章(资源服务端练习)

192 阅读2分钟

实现思路

使用 Node.js 的 http 模块创建一个 HTTP 服务器,通过解析请求的 URL 路径来判断请求的资源类型,对于静态资源,读取相应的文件并返回给客户端;对于动态请求,可以根据具体需求进行逻辑处理并返回响应。

示例代码

const http = require('http');
const fs = require('fs');
const path = require('path');

// 创建 HTTP 服务器
const server = http.createServer((req, res) => {
    // 获取请求的路径
    let filePath = '.' + req.url;
    if (filePath === './') {
        filePath = './index.html';
    }

    // 获取文件扩展名
    const extname = String(path.extname(filePath)).toLowerCase();
    const contentType = getContentType(extname);

    // 读取文件
    fs.readFile(filePath, (err, content) => {
        if (err) {
            if (err.code === 'ENOENT') {
                // 文件不存在,返回 404 错误
                res.writeHead(404, { 'Content-Type': 'text/html' });
                res.end('<h1>404 Not Found</h1>');
            } else {
                // 其他错误,返回 500 错误
                res.writeHead(500, { 'Content-Type': 'text/html' });
                res.end('<h1>500 Internal Server Error</h1>');
            }
        } else {
            // 文件读取成功,返回文件内容
            res.writeHead(200, { 'Content-Type': contentType });
            res.end(content, 'utf-8');
        }
    });
});

// 根据文件扩展名返回对应的 Content-Type
function getContentType(extname) {
    switch (extname) {
        case '.html':
            return 'text/html';
        case '.js':
            return 'text/javascript';
        case '.css':
            return 'text/css';
        case '.json':
            return 'application/json';
        case '.png':
            return 'image/png';
        case '.jpg':
            return 'image/jpg';
        case '.gif':
            return 'image/gif';
        default:
            return 'application/octet-stream';
    }
}

// 启动服务器
const port = 3000;
server.listen(port, () => {
    console.log(`Server running at http://localhost:${port}/`);
});

3. 代码解释

  • 引入模块:引入 httpfspath 模块。http 模块用于创建 HTTP 服务器,fs 模块用于文件操作,path 模块用于处理文件路径。
  • 创建服务器:使用 http.createServer() 方法创建一个 HTTP 服务器,并传入一个回调函数,该回调函数接收 req(请求对象)和 res(响应对象)作为参数。
  • 解析请求路径:根据请求的 URL 路径确定要读取的文件路径。如果请求的是根路径,则默认返回 index.html 文件。
  • 确定 Content-Type:通过 getContentType 函数根据文件扩展名确定响应的 Content-Type
  • 读取文件并返回响应:使用 fs.readFile 方法读取文件内容。如果文件不存在,返回 404 错误;如果读取过程中出现其他错误,返回 500 错误;如果文件读取成功,返回 200 状态码和文件内容。
  • 启动服务器:使用 server.listen() 方法启动服务器,并监听指定的端口。

4.测试一下

创建index.html

image.png 创建index.css

image.png

注掉css进行测试

image.png

image.png

解开css进行测试

image.png