Emrio
Emrio

Reputation: 111

express subdomain routing issue

I am using the express-subdomain module for my website but when I use this code :

const express = require('express')
const subdomain = require('express-subdomain')
const app = express()

const apiRouter = express.Router()
apiRouter.get('/', (req, res) => {
  res.send("Welcome to the API!")
})

app.use(subdomain('api', apiRouter))

app.get('/', (req, res) => {
  res.send("Main domain - Homepage")
})

app.get('/about', (req, res) => {
  res.send("Main domain - About")
})

I get the following results :

So the routes of the primary domain are also being applied for the subdomains. I have sought through Google, but nothing found :(

Any help on how to solve this would be greatly appreciated!

Upvotes: 2

Views: 900

Answers (1)

stdob--
stdob--

Reputation: 29167

For each subdomain, you need to handle a 404 error separately:

const express = require('express')
const subdomain = require('express-subdomain')
const app = express()
const apiRouter = express.Router()

apiRouter.get('/', (req, res) => {
  res.send("Welcome to the API!")
})

apiRouter.use((req, res, next) => {
  res.status(404)
  next(new Error('Not found'))
})

app.use(subdomain('api', apiRouter))

app.get('/', (req, res) => {
  res.send("Main domain - Homepage")
})

app.get('/about', (req, res) => {
  res.send("Main domain - About")
})

Upvotes: 2

Related Questions