图像未在 HTML 和 Nodejs 中显示(404 Not Found)

时间:2021-03-17 03:25:13

标签: javascript html node.js

我正在尝试将图像加载到我的 html 中,但是当我使用 nodejs 运行它时遇到了问题。找不到图片。

我的文件夹设置:

|-- server.js |-- 图片/ |--white-knight-logo.gif |-- JS |-- Node_Modules |-- 浏览量 |--index.html

我的 server.js 代码如下所示:

let customThrow = (message, code, statusCode) => {
  throw { message, code, statusCode };
}

我的 html 代码如下:

var express=require('express');
var app=express();
var  mysql=require('mysql');
var path = require('path');



app.set('views',__dirname + '/views');
app.use(express.static(__dirname + '/JS'));
app.use('/images', express.static('images'));  
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);



app.get('/',function(req,res){
  res.render('index.html');
  res.sendFile(__dirname + '/index.html');
  });



var server=app.listen(3000,function(){
console.log("We have started our server on port 3000");
});

这是我一直得到的图像。请帮忙。

<body>
   <div class="page">
        <img src='white-knight-logo.gif'>
   </div>

    <div class="bs-example">
        <input type="text" name="typeahead" class="typeahead tt-query" autocomplete="off" spellcheck="false" placeholder="Type your Query">

    </div>
            
</body>
</html>

1 个答案:

答案 0 :(得分:0)

当你开始使用 nodeJS 时,你需要有一个正确的文件夹结构。 您需要在主项目中有一个名为 public 的文件夹。 在公共文件夹中,创建另一个文件夹并将其命名为资产。 在 assets 文件夹中,创建另一个文件夹并将其命名为 images。然后,将所有图片添加到该图片文件夹中。

删除

app.use('/images', express.static('images')); 

并添加

app.use(express.static(__dirname + '/public')); 

然后,您可以像这样将图像路径添加到 html

<img src ="assets/images/nameofimage.jpg" ></img>

app.get('/',function(req,res){
  res.sendFile(__dirname + '/index.html');
  });

希望这会有所帮助。