user12674790
user12674790

Reputation:

Serving static files in Express dese not work

I have a folder named public in the root of my project . I would like to put all my images/css in that.

Now, I want to put the serving static section in the separate module named config:

//config.js

const express = require('express');  
module.exports = function (app) {
   app.use("/static", express.static(__dirname + '/public'));
}

then in the server.js

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

require('./startup/config')(app);

app.get('/', (req, res, next) => {
    res.send("Hi, How's it going ?")
})

app.listen(4500, () => {
    console.log("Server is running ...");
})

Now, when I want to call the following address

http://localhost:4500/static/xxx.jpg

I get the following error

Cannot GET /static/xxx.jpg

Structure Of Project :

-node_modules
-server.js
-public
-------xxx.jpg

Upvotes: 0

Views: 75

Answers (1)

RidgeA
RidgeA

Reputation: 1546

Your config.js file is located in /startup directory. __dirname refers to the directory where the current file located.

So you are trying to serve from ./startup/public instead of ./public

You could try to use process.cwd() instead of __dirname in your config.js file

Upvotes: 1

Related Questions