EFO
EFO

Reputation: 183

Routing in node: How can I mange the access to my public folder?

I'm sorry if I'm a little confusing in my explanation.

I Get this error on chrome when trying to reach my endpoint movies/add

GET http://localhost:3002/movies/css/style.css net::ERR_ABORTED 404 (Not Found) add:93 GET http://localhost:3002/movies/images/happy.svg 404 (Not Found) 2add:112 GET http://localhost:3002/movies/js/main.js net::ERR_ABORTED 404 (Not Found)

I have my files structured in a common way, and I have my routing using different paths, like this:

const iFeltRoutes = require('../app/routes/')
const movieRoutes = require('../app/routes/movies/') 
app.use('/movies', movieRoutes)
app.use('/', iFeltRoutes)

So when I access / and all the routes in iFeltRoutes, public folder is accessed the right way, but using the movieRoutes, gives me this error.

How can I define the right path to public folder, whatever the route I use?

Upvotes: 0

Views: 528

Answers (1)

1565986223
1565986223

Reputation: 6718

Relative path doesn't work very well when serving using express static. It's better to set up virtual path for all your static files and then use absolute path in your html etc

//Say folder structure
app.js
public
|  +-- css
|  |   +-- style.css
|  |   +-- another.css
|  +-- images
|  |   +-- some.jpg
app.use('/public', express.static(__dirname + "/public"))

// In you html
<link href="/public/css/style.css">
<img src="/public/images/some.jpg"></img>

Upvotes: 0

Related Questions