Home > Back-end >  How to serve static files from root path '/'
How to serve static files from root path '/'

Time:07-05

I understand that Express needs to be told where to serve static files from using something like server.use(express.static('public'); if all your static files reside in the public folder.

However there are static files in my app which MUST be served from the root of the site e.g.

I cannot create a separate route for each static file in the root folder because there can be many. When they are bundled up into the dist folder for deployment, they reside in the root of the site alongside the package.json file etc.

How can it be possible to serve the app's homepage at the route of '/' and also static files from that same route? e.g.:

server.use('/', express.static('/client')); 

server.get('/', async (req, res) => {
// serve homepage here
})

CodePudding user response:

var app = express()


app.use(express.static('folder_name'))

Or

app.use(express.static(__dirname   '/folder_mame'));
app.set('folder_name', __dirname);

CodePudding user response:

According to official docs:
Serving static files in Express
To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

The function signature is:

express.static(root, [options])
The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express static.

For example, use the following code to serve images, CSS files, and JavaScript files in a directory named public:

app.use(express.static('public'))

Now, you can load the files that are in the public directory:

http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html

Serving static files Express

  • Related