显示由NodeJS提供的静态html本地图像

Mat*_*att 0 html node.js express

我有一个可呈现index.html的NodeJS应用,但是我无法通过index.html在其所在的文件夹中找到图像。

这是index.js的内容

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get ('/', function(req, res){
    res.sendFile(__dirname + '/index.html');
});
http.listen(80, function(){
    console.log('listening on *:80');
});
Run Code Online (Sandbox Code Playgroud)

它可以成功提供index.html,但我提供的所有图像都是断开的链接。以下html不起作用

<img src="img/myimage.png">
Run Code Online (Sandbox Code Playgroud)

我的文件结构是

myApp - folder
    index.js
    index.html
    img - folder
        myimage.png
Run Code Online (Sandbox Code Playgroud)

我尝试了几种变体,例如

<img src="/img/myimage.png">
<img src="./img/myimage.png">
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用index.html将图像直接放置在app文件夹中,并尝试

<img src="myimage.png">
Run Code Online (Sandbox Code Playgroud)

但是到图像的链接仍然断开。

Abh*_*ash 5

const express = require("express");
const app = express();
Run Code Online (Sandbox Code Playgroud)

如果图像在名为“ Images”的文件夹中,并且要指向该文件夹中的图像为“ img / myimage.png”,请使用以下命令:

app.use('/img', express.static(__dirname + '/Images'));
Run Code Online (Sandbox Code Playgroud)

这样,您还可以将实际的图像文件夹名称保留为私有。