Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 872
crod Avatar asked Dec 22 '16 20:12

crod


1 Answers

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">
like image 88
Aruna Avatar answered Nov 15 '22 04:11

Aruna