简体   繁体   English

如何使用nodejs + NGINX实现REST API版本控制?

[英]How to implement REST API Versioning with nodejs + NGINX?

From past few days, I m working on How to implement API versioning with help of NGINX. 从过去的几天开始,我一直在研究如何在NGINX的帮助下实现API版本控制。

At an application level, I m able to implement But this required 2 Diff controller, 2 diff route, 2 diff model etc.. I don't want to do that. 在应用程序级别,我可以实现,但这需要2个Diff控制器,2个diff路由,2个diff模型等。我不想这样做。

I want two different projects like v1 and v2. 我想要两个不同的项目,例如v1和v2。 Using NGINX, If my URL contain v1 then it's point to v1 project and if URL contain v2 then it will Point to v2 project something like that. 使用NGINX,如果我的URL包含v1,则它指向v1项目;如果URL包含v2,则它将指向v2项目。

I know using NGINX ALIAS or ROOT we able to do that but I don't know how? 我知道使用NGINX ALIAS或ROOT我们可以做到这一点,但我不知道如何?

In fact, we are talking about how to configure nginx as a reverse proxy. 实际上,我们正在谈论如何将nginx配置为反向代理。 And do proxies for different projects, depending on the content of URL. 并根据URL的内容为不同的项目做代理。

In your case, you need to: 对于您的情况,您需要:

  1. Configure the sail-projects at different ports . 在不同的端口上配置sail-projects For example: 例如:

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

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

  2. Add to nginx configuration ( nginx.conf ) two upstream (for example for nginx and api-projects located on the same server). 添加到nginx配置( nginx.conf )中的两个上游 (例如,位于同一服务器上的nginx和api项目)。

  3. Add to nginx configuration ( nginx.conf inside server block) two locations for different api's. 在不同的api的两个位置添加到nginx配置(服务器块内的nginx.conf )。


Nginx configuration might look like this: 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;
  }

}

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

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