admin管理员组

文章数量:1426052

I'm trying to serve a very simple html page with one image. I'm using node.js and express. The html loads, but the image does not. Instead i am given the error GET https://localhost:3000/stockMarketPhoto.jpg 404 (Not Found) The image is in the same directory as everything else is. Somewhere I saw suggested that app.use(express.static('public')); is supposed to help with this, but no dice. I've tried both <img src="stockMarketPhoto.jpg"> and <img src="https://localhost:3000/stockMarketPhoto.jpg">. How can I get the image in my HTML page to load?

Here's the html in question

  <body>
    <img src="stockMarketPhoto.jpg">
  </body>

Here's the javascript.

const https = require('https');
const express = require("express")
const fs = require('fs');
let app = express();
app.use(express.static('public'));

app.listen(3000, () => {
  console.log("listening on 3000");
});

app.get('/', (req, res) => {
  console.log('connected');
  res.sendFile(__dirname + '/index.html')
})

I'm trying to serve a very simple html page with one image. I'm using node.js and express. The html loads, but the image does not. Instead i am given the error GET https://localhost:3000/stockMarketPhoto.jpg 404 (Not Found) The image is in the same directory as everything else is. Somewhere I saw suggested that app.use(express.static('public')); is supposed to help with this, but no dice. I've tried both <img src="stockMarketPhoto.jpg"> and <img src="https://localhost:3000/stockMarketPhoto.jpg">. How can I get the image in my HTML page to load?

Here's the html in question

  <body>
    <img src="stockMarketPhoto.jpg">
  </body>

Here's the javascript.

const https = require('https');
const express = require("express")
const fs = require('fs');
let app = express();
app.use(express.static('public'));

app.listen(3000, () => {
  console.log("listening on 3000");
});

app.get('/', (req, res) => {
  console.log('connected');
  res.sendFile(__dirname + '/index.html')
})
Share Improve this question edited Apr 3, 2018 at 17:10 David Sullivan asked Apr 3, 2018 at 16:46 David SullivanDavid Sullivan 5148 silver badges21 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

First i remend you read this from the express docs. Serving Static files in express

and in here:

<img src="stockMarketPhoto.jpg">

you are missing a '/' should look like this:

<img src="/stockMarketPhoto.jpg">

Your image should be inside the public folder in your app. What i do is usually put an Image, Javascript, and css folder inside my public folder and import them like this:

src='/Image/example.jpg'
src='/Javascript/example.js'
src='/css/master.css'

Basically when you tell express to serve your static files in the public folder, express then interprets the above example like this.

'public/Image/example.jpg'

本文标签: javascriptImage not found in webpage served with nodejs and expressStack Overflow