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.
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">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With