【转载】Node 本地网站服务器网页加载不出图片的解决方法

753 阅读1分钟

版权声明:本文为CSDN博主「_lmmmmmm」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:blog.csdn.net/Lai_im/arti…

文章目录

前言

遇到的问题

源代码

前言

最近在自学 Node.js 准备入门前端

在用 Node 配置本地网站服务器的时候连上了自己期末的前端综合实验设计的作业

遇到了一些问题来记录一下。

遇到的问题

1. 连接网站的时候加载不出页面图片。

image.png

解决:因为使用 fs.readFile() 来读取所有的文件,其中包括 HTML、CSS、JS 以及各种格式的图片文件。众所周知 readFile() 有三个参数,需要将第二个参数删去,这样网页就可以正常的加载图片了。

image.png

2. 点击网站跳转链接的时候找不到页面文件 -> 简单来说就是路径不对。

解决:这里我用了简单的路径判断,如果访问的文件是以.html 格式结尾的话,则在路径前添加存放html 文件的路径。

源代码

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

const app = http.createServer();

app.on('request', (req, res) => {

    let pathname = url.parse(req.url).pathname;
    pathname = pathname.endsWith('.html') ? 'html/' + pathname : pathname;
    let realPath = path.join('/Volumes/Code & MD/Web/Web综合设计', pathname);
    console.log(realPath);

    fs.readFile(realPath, (err, doc) => {
        if (err != null) {
            res.writeHead(404, {
                'content-type': 'text/html; charset=utf8'
            });
            res.end('404 Not Found');
            return;
        }
        
        res.end(doc);
    });
});

app.listen(3000);
console.log('启动服务器成功');