简体   繁体   English

Express-子域路由无法正常工作?

[英]Express-subdomain routing not working correctly?

I have been looking for solutions for a couple days now trying to google it and all and now i am here. 我一直在寻找解决方案,现在尝试使用Google及其它,现在我在这里。 I am trying to setup subdomains for my app using express-subdomain package. 我正在尝试使用express-subdomain包为我的应用设置子域。 However in the example below the app ALWAYS returns app.get route and skips the other subdomain routes specified. 但是,在下面的示例中,应用程序始终返回app.get路由,并跳过指定的其他子域路由。 I have also in turn added the hosts file url so i know that should not be the issue. 我也依次添加了主机文件url,所以我知道这不是问题。

It must be in my code for some reason it always ends up displaying Detect Region route even when accessing oce.localhost:3000. 由于某种原因,它必须出现在我的代码中,即使访问oce.localhost:3000,它也总是会显示“检测区域”路由。

Please help me :) 请帮我 :)

Server.js Server.js

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

// Region routes
var router = express.Router();
var na = require('./routes/region/na.js');
var oce = require('./routes/region/oce.js');

router.use(subdomain('na.localhost', na));
router.use(subdomain('oce.localhost', oce));

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

app.listen(3000);

routes/region/oce.js 路线/区域/oce.js

var
  express = require('express'),
  router = express.Router();

router.get('/', function(req, res) {
    res.send('Your are in OCE Region!');
});

module.exports = router;

And na.js is pretty much the name as oce.js na.js几乎与oce.js一样

Cheers 干杯

You are setting your subdomains in the router variable but you don't tell your app to use it. 您可以在router变量中设置子域,但不要告诉您的应用使用它。

You have to do that : 您必须这样做:

app.use(router);

You put it in place of your current app.get . 您将其替换为当前的app.get


Edit 编辑

You could also put your app.get after the app.use(router) so that it will act as a default route. 您也可以将app.get放在app.use(router)以便将其用作默认路由。 (When you are neither on oce or na , it will use it) (当您不在ocena ,它将使用它)


Edit after some testing 经过一些测试后编辑

Alright I've been able to make it work using express-vhost . 好了,我已经能够使用express-vhost使其工作。 I just updated your server.js like so : 我只是这样更新您的server.js

 var subdomain = require('express-vhost'); var express = require('express'); var app = express(); // Region routes var router = express.Router(); var na = require('./routes/region/na.js'); var oce = require('./routes/region/oce.js'); subdomain.register('na.localhost', na) subdomain.register('oce.localhost', oce) 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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM