1

I am using the example setup from the https://www.npmjs.com/package/express-subdomain package. However, when I try api.localhost:3000 in a browser it throws an error: "Cannot GET /"

How can I get api.localhost:3000 running? I would consider other solutions, not just ones using express-subdomain as long as you don't have to type in the fqdn in the setup.

app.js:

var subdomain = require('express-subdomain');
var express = require('express');
var app = express();

// *** Code examples below go here! ***
var router = express.Router();

//api specific routes
router.get('/', function(req, res) {
    res.send('Welcome to our API!');
});

router.get('/users', function(req, res) {
    res.json([
        { name: "Brian" }
    ]);
});

app.use(subdomain('api', router));
app.listen(3000);

package.json:

{
  "name": "auth_manager",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.3",
    "express-subdomain": "^1.0.5"
  }
}
GavinBelson
  • 2,514
  • 25
  • 36

2 Answers2

1

I think that the API is alive at http://api.example.com/ and not in the api.localhost:3000. However if you want to run them locally I suggest that you follow https://www.npmjs.com/package/express-subdomain#developing-locally

Giannis
  • 312
  • 2
  • 5
  • 16
0

If you plan to use this middleware while developing locally, you have to ensure that your subdomain is listed in your hosts file. Refer here.

On MacOS:

  1. Adjust host file to forward requests from url:

    sudo nano /etc/hosts

    127.0.0.1 myapp.dev

    127.0.0.1 api.myapp.dev

  2. Clear cache:

    sudo killall -HUP mDNSResponder

  3. In express:

    app.use(subdomain('api', router));

  4. Any authentication middleware needs to be adjusted to authenticate api.myapp.dev not localhost

  5. In Chrome you can use the api.myapp.dev url

  6. If you are using SSL (https) and have a self signed cert: Chrome usually blocks the hostfile URL if it is not localhost. Then, you need to click anywhere in the Chrome window and literally type in thisisunsafe and it will let you through. Refer to this ticket.

GavinBelson
  • 2,514
  • 25
  • 36