简体   繁体   中英

Displaying local images in static html served by NodeJS

I have a NodeJS app that renders index.html, but I can't get index.html to find the images in the folder it's located in.

Here are the contents of 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');
});

It serves index.html successfully but all images I supply it are broken links. The following html does not work

<img src="img/myimage.png">

and my file structure is

myApp - folder
    index.js
    index.html
    img - folder
        myimage.png

I've tried several variations such as

<img src="/img/myimage.png">
<img src="./img/myimage.png">

I've also tried placing the image directly in the app folder with index.html and trying

<img src="myimage.png">

But the link to the image is still broken.

const express = require("express");
const app = express();

If you have the images in a folder named "Images" and you want to point to the image in the folder as "img/myimage.png" , then use this:

app.use('/img', express.static(__dirname + '/Images'));

This way you can also keep your actual images folder name private.

I was able to resolve the issue by changing

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

into

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

I then added

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

Do you mean broken links in the browser ? so the browser can not open the links rendered in index.html ?

The browser will probably need full paths to the images .. it doesn't seem that your node server is sending the full paths in the index.html file it passes to the browser.. have a look on that ..

In the declaration of static file you will use in the express app, you have to put your files (images, songs, file) into public folder. Then, your express and ejs will show your file from the public folder as a root of that file.

var express = require("express");
var app     = express();

app.use(express.static('public'));
app.set("view engine", "ejs");

app.get("/", function(req, res){
  res.render("main");
});

app.listen(3000, function(req, res){
  console.log("Auth server started!");
});

EJS folder is right here.

<h1>Secret Page!</h1>

<img src="anna.jpg"/>

<img src="https://i.imgur.com/NcXbX08.jpg" alt="">

After all, reload your nodejs app.

项目目录必须如下所示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM