Milos Krstic
Milos Krstic

Reputation: 21

How can I serve 2 different folders using express (Client and Admin)

I'm trying to build an admin panel for my node.js app. My current folder structure looks like this:

client (folder)
  images (folder)
  fonts (folder)
  index.html
  index.css
  index.js

app.js (node.js server code)
package.json

I want to have another folder in that root, looking like this:

admin (folder)
  index.html
  index.css
  index.js

Having only 2 lines of express code in my node.js app (see below), I have tried the first 'logical' thing.

app.use(express.static(path.join(__dirname, 'client')))
app.use(express.static(path.join(__dirname, 'admin')))

app.get('/admin', (req, res) => res.sendFile(`${__dirname}/admin/index.html`))
app.get('*', (req, res) => res.sendFile(`${__dirname}/client/index.html`))

But it obviously doesn't work, throws some weird error on the index.html line 1 that '<' is an invalid character or something, so it's broken.

Code:

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

app.get('*', (req, res) => res.sendFile(`${__dirname}/client/index.html`))

This is really all the code I use with express currently, and to be honest, I don't even understand it very well. All the routing is done on the client-side, tho, and it works perfectly fine for now.

What I am trying to accomplish here is, whatever route user navigates to, he gets redirected to my client app, and front-end router does the rest (IE localhost:8080/, or localhost:8080/ps4/games...). But if I go to localhost:8080/admin, and only in that case, I want to serve an admin panel, from where I can log in and manage my products, menu items, answer chat messages, etc.

Thanks!

Upvotes: 1

Views: 1212

Answers (1)

Felipe Toledo
Felipe Toledo

Reputation: 615

You can replace these 4 lines of your code:

app.use(express.static(path.join(__dirname, 'client')))
app.use(express.static(path.join(__dirname, 'admin')))

app.get('/admin', (req, res) => res.sendFile(`${__dirname}/admin/index.html`))
app.get('*', (req, res) => res.sendFile(`${__dirname}/client/index.html`))

with these:

app.use('/', express.static(__dirname +'/client'));
app.use('/admin', express.static(__dirname +'/admin'));

The above express's built in functions allow you to host static files with the path you want. You can find more information about hosting static files in express's documentation at http://expressjs.com/en/starter/static-files.html

Upvotes: 2

Related Questions