Why the subdomains are not working with express.js?

折月煮酒 提交于 2019-12-12 03:45:31

问题


so I am experimenting with it locally, this is in my hosts file

127.0.0.1       example.dev
127.0.0.1       www.example.dev
127.0.0.1       api.example.dev

and this is my code:

var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
var router = express.Router();

// example.com 
app.get('/', function(req, res) {
    res.send('Homepage');
});

//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);

it's basically the example from the package website api.example.dev/users works well, but when I go to to api.example.dev the content is the same as on example.dev (like it is overwritten) any ideas what I am doing wrong? thanks


回答1:


This is a order of requests processing problem. Move the declaration of the request handler for the main domain after the subdomain:

var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
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));

// example.com 
app.get('/', function(req, res) {
    res.send('Homepage');
});

app.listen(3000);


来源:https://stackoverflow.com/questions/42888960/why-the-subdomains-are-not-working-with-express-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!