You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Node.js服务器localhost下图片无法显示问题求助(游戏商城网站开发)

解决Node.js服务器无法加载图片的问题

嘿,我来帮你搞定这个图片加载的问题!你遇到的核心问题是当前的Node.js服务器只处理了访问home.html的请求,当浏览器尝试加载图片r6.webp时,服务器不知道该怎么响应它——这就是为什么直接打开HTML能看到图,但通过localhost访问就不行。

问题分析

当你通过浏览器访问localhost:3000时,服务器返回了home.html。但浏览器解析HTML时,会单独发送一个请求去获取<img src="r6.webp">对应的资源,这时候你的服务器还是按照原来的逻辑去读取home.html,要么返回错误,要么返回HTML内容,而不是图片文件,所以图片加载失败。

解决方案:修改服务器代码处理静态资源

你需要修改server.js,让它能根据不同的请求路径返回对应的文件,并且设置正确的HTTP响应头(比如图片的Content-Type)。

首先确认你的文件结构是这样的(所有文件在同一个文件夹下):

你的项目目录/
├── server.js
├── home.html
└── r6.webp

然后替换server.js为以下代码:

const http = require('http')
const fs = require('fs')
const path = require('path') // 引入path模块处理文件路径
const port = 3000

const server = http.createServer(function(req, res) {
  // 确定要读取的文件路径
  let filePath = '.' + req.url;
  // 如果请求根路径,默认返回home.html
  if (filePath === './') {
    filePath = './home.html';
  }

  // 根据文件扩展名设置对应的Content-Type
  const extname = path.extname(filePath);
  let contentType = 'text/html';
  switch (extname) {
    case '.js':
      contentType = 'text/javascript';
      break;
    case '.css':
      contentType = 'text/css';
      break;
    case '.webp':
      contentType = 'image/webp';
      break;
    // 可以添加更多文件类型,比如.png、.jpg等
    case '.png':
      contentType = 'image/png';
      break;
    case '.jpg':
      contentType = 'image/jpeg';
      break;
  }

  // 读取文件并返回
  fs.readFile(filePath, function(error, data) {
    if (error) {
      if(error.code === 'ENOENT') {
        // 文件不存在时返回404
        res.writeHead(404, {'Content-Type': 'text/html'});
        res.write('Error: File Not Found');
      } else {
        // 其他服务器错误返回500
        res.writeHead(500);
        res.write('Server Error: ' + error.code);
      }
    } else {
      // 成功读取文件,设置正确的Content-Type并返回数据
      res.writeHead(200, {'Content-Type': contentType});
      res.write(data);
    }
    res.end();
  })
})

server.listen(port, function(error){
  if (error) {
    console.log('something went wrong', error)
  } else {
    console.log('server is listening on port ' + port)
  }
})

代码说明

  • path模块:用来处理文件扩展名,帮我们设置正确的Content-Type,确保浏览器能识别返回的资源类型。
  • 根据请求路径处理文件:当请求根路径/时返回home.html,请求/r6.webp时返回对应的图片文件。
  • 错误处理:区分文件不存在(404)和服务器内部错误(500),返回更清晰的错误信息。

进阶简化方案(可选)

如果你以后要处理大量静态资源(比如CSS、更多图片、JS文件),可以使用Express框架的express.static中间件,它能自动处理静态资源的请求,不用手动写上面的逻辑。比如:

const express = require('express');
const app = express();
const port = 3000;

// 让Express托管当前目录下的静态资源
app.use(express.static(__dirname));

// 根路径返回home.html
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/home.html');
});

app.listen(port, () => {
  console.log('server is listening on port ' + port);
});

当然,使用Express需要先通过npm install express安装它。

这样修改后,重启你的Node.js服务器,再访问localhost:3000就能看到图片正常显示啦!

内容的提问来源于stack exchange,提问作者Jonathan Dasilva

火山引擎 最新活动