【问题标题】:Express-subdomain not seeing routeExpress-subdomain 没有看到路由
【发布时间】:2019-02-26 00:13:41
【问题描述】:

我正在使用https://www.npmjs.com/package/express-subdomain 包中的示例设置。但是,当我在浏览器中尝试 api.localhost:3000 时,它会引发错误:“Cannot GET /”

如何让 api.localhost:3000 运行?只要您不必在设置中输入 fqdn,我会考虑其他解决方案,而不仅仅是使用 express-subdomain 的解决方案。

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"
  }
}

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    我认为 API 在 http://api.example.com/ 处有效,而不是在 api.localhost:3000 中。但是,如果您想在本地运行它们,我建议您关注 https://www.npmjs.com/package/express-subdomain#developing-locally

    【讨论】:

    • 主机文件仍有问题。它可以在没有子域的情况下工作,但不能与它一起工作。
    【解决方案2】:

    如果您打算在本地开发时使用此中间件,则必须确保您的子域在您的 hosts 文件中列出。参考here

    在 MacOS 上:

    1. 调整主机文件以转发来自 url 的请求:

      sudo nano /etc/hosts

      127.0.0.1 myapp.dev

      127.0.0.1 api.myapp.dev

    2. 清除缓存:

      sudo killall -HUP mDNSResponder

    3. 快递:

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

    4. 任何认证中间件都需要调整为认证api.myapp.dev而不是localhost

    5. 在 Chrome 中,您可以使用 api.myapp.dev 网址

    6. 如果您使用 SSL (https) 并拥有自签名证书:如果不是 localhost,Chrome 通常会阻止主机文件 URL。然后,您需要单击 Chrome 窗口中的任意位置并按字面意思输入thisisunsafe,它会让您通过。参考这个ticket

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 2020-11-30
      相关资源
      最近更新 更多