edddd
edddd

Reputation: 482

Is there a way to avoid using app.get() for every static file in express?

I'm starting out with express.js and trying to serve lots of static files from the server (could be .css, .jpg, .svg, .js or other file types). Is there a way to do this without typing app.get() for each file? I know about express.Router() but then the clutter just goes over into another file.

Upvotes: 0

Views: 213

Answers (1)

Danila
Danila

Reputation: 18476

You might want to use express.static middleware.

For example, use the following code to serve all the files from 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

More info here: https://expressjs.com/en/starter/static-files.html

Upvotes: 2

Related Questions