Angular 5 反向代理配置

一、webpack server 方式

这里所说的反向代理仅限于基于Angular-cli创建的HTTP Server,也就是通过ng、cnpm、npm启动的Server。

  1. 在项目根目录新建proxy.config.json
  2. 填入以下内容
{
  "/api": {
    "target": "http://localhost:8080",
    "secure": "false",
    "pathRewrite": {
      "^/api": ""
    }
  }
}
  1. 启动程序时 添加 –proxy proxy.config.json
    ng serve --proxy proxy.config.json

 或者编辑package.json:

    "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy proxy.config.json --host xxx.com --port 80",# 在ng server之后添加--proxy proxy.config.json
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

然后直接以cnpm(npm) start启动项目即可。

关于Angular Proxy的更多信息,可以查看官方文档:
Angular Proxy

二、nginx.conf 配置示例

实际的生产环境我用的是nginx,这里也把简单的配置发出来。

nginx.conf:

  ...
  gzip on;
  gzip_min_length 1k;
  gzip_buffers 4 16k;
  gzip_http_version 1.1;
  gzip_disable "MSIE [1-6].";
  gzip_comp_level 4;
  gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
  gzip_vary off;
  # 后端服务器
  upstream myserver {
      server 127.0.0.1:8080;
      keepalive 2000;
  }
  server {
      listen       80;
      #域名 
      server_name  xxx.com;
      charset utf-8;
      #access_log  logs/host.access.log  main;
      error_page  404              /404.html;
      # redirect server error pages to the static page /50x.html
      #
      error_page   500 502 503 504  /50x.html;
      location = /50x.html {

      }
      location / {
         # ng build生成的文件夹目录
         root   /Users/qiqj/WebstormProjects/ng5-base/dist;
         try_files $uri $uri/ /index.html =404;
         index  index.html;
      }
      location ~ ^\.(js)$ {
          # ng build生成的文件夹目录
          root /Users/qiqj/WebstormProjects/ng5-base/dist;
      }
      # 静态文件
      location /assets {
          alias /Users/qiqj/WebstormProjects/ng5-base/dist/assets/;
      }
      # 后端请求代理转发
      location /api/ {
          # http://myserver/ #最后一个斜杠不可少,否则接口url会带上/api/目录
          proxy_pass   http://myserver/;
          proxy_set_header x-forwarded-host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header REMOTE-HOST $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;            
          proxy_redirect  off;  
          client_max_body_size    2000m;
      }
    }

你可能感兴趣的:(Nginx,工具)