【问题标题】:How to implement REST API Versioning with nodejs + NGINX?如何使用 nodejs + NGINX 实现 REST API 版本控制?
【发布时间】:2017-06-14 13:44:41
【问题描述】:

过去几天,我正在研究如何在 NGINX 的帮助下实现 API 版本控制。

在应用程序级别,我可以实现但这需要 2 个 Diff 控制器、2 个 diff 路由、2 个 diff 模型等。我不想这样做。

我想要两个不同的项目,例如 v1 和 v2。使用 NGINX,如果我的 URL 包含 v1,那么它指向 v1 项目,如果 URL 包含 v2,那么它将指向 v2 项目类似的东西。

我知道使用 NGINX ALIAS 或 ROOT 我们可以做到这一点,但我不知道怎么做?

【问题讨论】:

    标签: node.js nginx sails.js api-versioning


    【解决方案1】:

    其实我们讲的是如何将nginx配置为反向代理。并根据URL的内容为不同的项目做代理。

    在您的情况下,您需要:

    1. 配置sail-projects at different ports。例如:

      对于 API.V1:sails.config.port -> 3010

      对于 API.V2:sails.config.port -> 3020

    2. 添加到 nginx 配置 (nginx.conf) two upstream(例如用于位于同一服务器上的 nginx 和 api 项目)。

    3. 添加到 nginx 配置(nginx.conf 内部服务器块)two locations 用于不同的 api。


    Nginx 配置可能如下所示:

    upstream api_v1 {  
      server 127.0.0.1:3010;
      keepalive 64;
    }
    
    upstream api_v2 {  
      server 127.0.0.1:3020;
      keepalive 64;
    }
    
    server {  
      listen        80;
      server_name   example.com;
    
      location /api/v1 {
        proxy_pass                          http://api_v1;
        proxy_http_version                  1.1;
        proxy_set_header  Connection        "";
        proxy_set_header  Host              $host;
        proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header  X-Real-IP         $remote_addr;
      }
    
      location /api/v2 {
        proxy_pass                          http://api_v2;
        proxy_http_version                  1.1;
        proxy_set_header  Connection        "";
        proxy_set_header  Host              $host;
        proxy_set_header  X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header  X-Real-IP         $remote_addr;
      }
    
    }
    

    【讨论】:

    • 我会尝试然后告诉你
    猜你喜欢
    • 2012-05-31
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 2023-01-28
    • 2018-09-30
    • 1970-01-01
    相关资源
    最近更新 更多