I'm facing a problem with express. It doesn't serve any static file !! I tried so many solutions but no one works. this is the code
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.static(__dirname 'public'));
port = process.env.PORT || 3000
app.listen( port, () => {
console.log("running on port " port )
})
I tried to make it
app.use('public' , express.static(__dirname 'public'))
and
app.use('public' , express.static(path.join(__dirname , 'public')))
and
app.use(express.static(path.join(__dirname , 'public')))
but still not working !! files structure is
|test==> project name
|public
|_test.html
|index.js
CodePudding user response:
If your structure is like this:
|test==> project name
|public
|_test.html
|index.js
__dirname
will give you the current directory name your index.js
file is in, so it will not include another /
at the end. You will need to add the public folder like this: app.use(express.static(__dirname '/public'));
Or more simply you can use app.use(express.static('public'))
CodePudding user response:
try this way :
app.use('/public', express.static('public'));
CodePudding user response:
You miss the / before public. try path.join(__dirname, '/public')