'How to access files in my public folder in node.js express

I am trying to access files located in my public folder, using express. My file structure looks like this

/app
 -app.js
 /routes
  -index.js
 /public
  /images
   /misc
   -background.jpg
  /css
    -style.css

My app.js is running on port 3000,

app.use(express.static('app/public'));
app.use(require('./routes/index'));

and index.js cannot find background.jpg or style.css

router.get('/',function(req,res){
res.send(`
<link rel="stylesheet" type="text/css"
  href="css/style.css">
<h1>Welome</h1>
<img
src="/images/misc/background.jpg"
style="height:300px;"/>
<p>some text</p>`);
});

module.exports = router;

I am going by the docs so I have no idea why this is not working.



Solution 1:[1]

As your app.js and public folders are inside the app folder, you don't need to include the app folder in express.static('app/public') and also use path.resolve as below,

var path = require('path');

app.use(express.static(path.resolve('./public')));

Also, change the href value below to href="/css/style.css",

<link rel="stylesheet" type="text/css"
  href="/css/style.css">

Solution 2:[2]

Require path module in app.js:

var path=require('path');

Modify middle ware for static content:

app.use(express.static(path.join(__dirname,'public')));

Link to your css like this:

<link rel="stylesheet" type="text/css" href="/css/style.css">

Solution 3:[3]

Obviously an old question, adequately answered, but here's how to make it available at a distinct path

app.use('/u/profileImg/', express.static('./userCreated/profileImg/'));

Where the first argument is the web-accessible path, and the second argument is the location of the folder.

You can also do

app.use('/u/', express.static('./userCreated/'));

and /u/profileImg/ would still be available, as well as the other contents of /userCreated/.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aruna
Solution 2 Lakshay Kapoor
Solution 3 Regular Jo