access Node.JS Express static directory from different routes

时间:2018-01-23 19:16:00

标签: node.js express web

I have a NodeJS with Express and I'm using Gulp to build the app

public folder is source code folder for script and style files, and dist is a folder for Gulp output that contains all css, js, ejs files

my file structure is this:

|-app.js
|-server.js
|-routes
    |-loginRoute.js
    |-appRoute.js
|-views
    |-loginViews
        |-login.ejs
    |-index.ejs
|-public
    |-scripts
        |-script files...
    |-style
        |-css files...
|-dist
    |-scripts
        |-script files...
    |-css
        |-css files...
    |-loginViews
        |-login.ejs
    |-index.ejs

I set dist folder as a static folder like this:

app.use(express.static(path.join(__dirname, 'dist')));

and all .ejs views served from dist folder.

When I try to access http://localhost:8080/login Express render login.ejs that placed in dist/login folder, and I got an error when the page tries to load script and css files that those files don't exist under http://localhost:8080/login/somefile

But, when views served from views folder, and static folder set like

app.use(express.static(path.join(__dirname, 'public')));

and I try to access to http://localhost:8080/login, Express render login.ejs that placed in views/login folder, the browser able to load css and script files from the static folder

0 个答案:

没有答案