在nginx上托pipestatic angular2应用程序,并将http请求代理到后端api

如何获取angular2路由,并将http请求委托给另一台机器上的其他api?

我有一个服务于静态html文件的nginx服务器上的angular2 web应用程序。 我有一个单独的restapi托pipe在不同的机器上有不同的IP地址。 我已经将位置设置为/在我的nginxconfiguration文件中,以允许angular2path正常工作。 我还添加了一个位置/ API /我希望将拦截任何API请求,并将其代理到我的后端API。

我的nginx conf与代理设置为http://swapi.co用于testing目的。

events { worker_connections 4096; ## Default: 1024 } http { server { listen 80; server_name localhost; root /usr/share/nginx/html; index index.html index.htm; include /etc/nginx/mime.types; location / { # If you want to enable html5Mode(true) in your angularjs app for pretty URL # then all request for your angularJS app will be through index.html try_files $uri /index.html; } # /api will server your proxied API that is running on same machine different port # or another machine. So you can protect your API endpoint not get hit by public directly location /api/ { proxy_pass http://swapi.co; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } #Static File Caching. All static files with the following extension will be cached for 1 day location ~* .(jpg|jpeg|png|gif|ico|css|js)$ { expires 1d; } } } 

我的angular2服务

 import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; @Injectable() export class Service { private url: string = '/api/people/'; constructor (private http: Http) {} getPeople () { return this.http.get(this.url) .map(res => res.json()); } } 

任何帮助将非常感激。

得到它在我的开发环境中正确代理请求。 添加到http块并指向代理传递给上游的api值

 upstream api { server 192.168.0.15:9998; } 

完整的配置:

 events { worker_connections 4096; ## Default: 1024 } http { # Change this depending on environment upstream api { server 192.168.0.1:9998; } server { listen 80; server_name localhost; root /usr/share/nginx/html; index index.html index.htm; include /etc/nginx/mime.types; location / { # If you want to enable html5Mode(true) in your angularjs app for pretty URL # then all request for your angularJS app will be through index.html try_files $uri /index.html; } # /api will server your proxied API that is running on same machine different port # or another machine. So you can protect your API endpoint not get hit by public directly location /api { proxy_pass http://api; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } #Static File Caching. All static files with the following extension will be cached for 1 day location ~* .(jpg|jpeg|png|gif|ico|css|js)$ { expires 1d; } } }