简体   繁体   中英

Setting up an Express JS app

I'm using express for my application. Currently, when I run the server and open the browser to my local host, the index page that I want to do a GET request to is displayed. The problem is, there's supposed to be an image on the page, and it isn't displaying

GET http://localhost:3000/public/img/ssi.png 404 (Not Found)

I'm getting a 404 not found, I'm confused because I know in my html, the file path to that image is correct

    <a href="index.html"><img src="../public/img/ssi.png"></a>

this is my file structure:

  • express_app
    • node_modules
    • public
      • css
      • img
        • ssi.png
      • js
    • router
    • views
      • index.html

below is my server code

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

app.set('views', __dirname + '/views');
app.set('public', __dirname + '/public');
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.get('/',function(req,res){
        res.render('index.html');
     });
app.get('/about',function(req,res){
        res.render('about.html');
    });

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

Somebody, anybody, please help!!!

Your don't need to put relative paths in your html file. Just the path starting from the public folder of your project.

You should also use the static files api from express in order to serve static files (usually inside the public folder). Here is how you do it:

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

So, in your example, it should be accessible using <img src="img/ssi.png">

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