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.
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.
Share Improve this question edited Dec 22, 2016 at 20:53 Aruna 12k3 gold badges30 silver badges42 bronze badges asked Dec 22, 2016 at 20:43 crodcrod 2353 gold badges5 silver badges12 bronze badges 2 |3 Answers
Reset to default 13As 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">
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">
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/
.
http://localhost:3000/css/style.css
, what exactly do you get? – Kevin B Commented Dec 22, 2016 at 20:45