Subdomains not working using express-vhost

475 Views Asked by At

new to Stack Overflow.

So I'm hosting my website using Express (Node 9) on a Digital Ocean droplet. I'm using express-vhost so I can detect subdomains to allow me to do api.example.com instead of example.com/api but when I try it, it just directs me to example.com while still having the api. part in the hostname.

I'm not sure if this is a programming problem or if it's actually something to do with my DNS records or maybe Digital Ocean is the problem. I'm not well equipped with knowledge of VPSes and hosting.

Here's the code:

// app.js
var subdomain = require('express-vhost');
var express = require('express');
var app = express();
var router = express.Router();
var api = require("./api.js")

subdomain.register('api.localhost:3000', api)
app.use(subdomain.vhost(app.enabled('trust proxy')));

app.get('/', function(req, res) {
    res.send('Detect Region and send to correct subdomain!');
});

app.listen(3000);

and the other file

// api.js
var express = require('express')
var router = express.Router()

router.get('/', function(req, res) {
    res.send("api url")
});

module.exports = router;

Sorry if this isn't enough information. Happy to answer any other questions you need answered.

-- sys

1

There are 1 best solutions below

1
On

I suggest you not to use express-vhost (old and deprecated package) but directly the vhost module of the express org.

const vhost = require('vhost')
const express = require('express')
const app = express()
const api = require('./api')

app.enable('trust proxy')

app.use(vhost('api.localhost:8000', api)) // api being your router

app.get('/', function(req, res) {
    res.send('Detect Region and send to correct subdomain!');
})

app.listen(3000)