将动态子域与 nodejs 一起使用 [英] use dynamic subdomains with nodejs
问题描述
你好,我是 Nodejs 的新手.我想使用动态子域来访问我的 API,并通过子域前缀我可以管理我的 API 数据.
hello i am new to Nodejs. I want to use dynamic subdomains to access my API and through subdomain prefix I can manage my API data.
假设我给了像 domain:3000 这样的域,子域可以是 a.domain:3000 或 b.domain:3000 或任何以 domain:3000 为前缀的内容.
Suppose I gave domain like domain:3000 and sub-domain could be a.domain:3000 or b.domain:3000 or anything prefixed to domain:3000.
我使用了通配符域.但仍然无法理解流程以及如何使用它并允许在 DB 中列出组织(将前缀视为组织名称).
I used wildcard-domains. but still unable to undersatnd the flow and how to use it and allow organisation listed in DB (Consider prefix as organisation name).
我使用了以下代码:
var wildcardSubdomains = require('wildcard-subdomains')
var checkUser = subdomain('*.localhost:3000', function(req, res,
next) {
console.log(req.session.user.valid);
if(!req.session.user.valid) {
return res.send('Permission denied.');
}
next();
});
app.use(checkUser);
我也在使用 angularjs 并使用 ui.router 来更改我的状态或网址.
I am also using angularjs and using ui.router to change my states or urls.
推荐答案
我用过这个模块
npm i vhost --save
这里可以看到信息http://expressjs.com/en/resources/middleware/vhost.html
正如您在 https://www.npmjs.com/package/wildcard-subdomains 中所见
app.use(wildcardSubdomains({
namespace: 's', // __NAMESPACE_FROM_WILDCARD_CONFIG__
www: 'false',
}))
如果你按照,例如,链接 foo.localhost:3000 Express 将处理这个中间件
If you follow, example, link foo.localhost:3000 Express will process this middleware
app.get('/s/foo/', function(req, res){
res.send("Meow!")
})
也就是说
app.get('/__NAMESPACE_FROM_WILDCARD_CONFIG__/__SUBDOMAIN__/', function(req, res){
res.send("Meow!")
})
你可以试试写app.get('/s/:subdomain', ...
这篇关于将动态子域与 nodejs 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!