Zak
Zak

Reputation: 940

Failed to load resource: the server responded with a status of 404 (Not Found) issue in Nodejs app

I need help. I looked up the solutions here but still couldn't find it. So I'm practicing something in Goorm ide and I have come to a dead-end. I am trying to link main.js(which is in js folder) file by putting the script in the footer. But I'm getting an error which says

Failed to load resource: the server responded with a status of 404 (Not Found) I also uploaded some png files in lib folder and I'm getting the same error after trying to access those in an ejs template.

Root folder consists of js, lib and views folder and some others which are not relevant.

To link the main.js in footer.ejs(which is in partials folder inside views), I used <script type="text/javascript" src="../../js/main.js"></script>. The png images which are uploaded in lib/images folder, I tried to access those from an ejs template in views so I used <img src="../lib/images/image1.png">. I am getting that error in both the cases. It would be highly appreciated if someone could help. This is how my root folder looks like - enter image description here

EDITED: This is the app.js code:

require('dotenv').config();
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var indexRoute = require("./routes/index");
var flash = require("connect-flash-plus");
var session = require('express-session');

// APP CONFIG
app.use(express.static(__dirname + "/public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended:true}));
app.set('json spaces', 2);
app.use(session({
    secret: 'boom',
    cookie: { maxAge: 60000 },
    saveUninitialized: true,
    resave: true
}));

app.use(flash());

app.use(function(req, res, next) {
    res.locals.error = req.flash("error");
    next();
});


// routes

app.use(indexRoute);

app.listen(3000, function(){
    console.log("Server has started");
})

Upvotes: 5

Views: 13668

Answers (1)

jknotek
jknotek

Reputation: 1864

Your Express configuration specifies that all of your static files will be accessed from the public directory:

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

This means that any files you want to access in your web browser must be within this directory (or a subdirectory of it).

For instance, if you want to access main.js, and it's location in public/main.js, you would access it on the frontend like this:

<script type="text/javascript" src="/main.js"></script>

Note that on the frontend, you must not include the public/ prefix.

Upvotes: 7

Related Questions