美文网首页
angular proxy 配置

angular proxy 配置

作者: 4f4e62418dff | 来源:发表于2022-03-27 11:11 被阅读0次

    在项目文件夹下创建proxy.config.json文件:

    {
      "/api": {
        "target": "http://api-dev..com",
        "logLevel": "debug",
        "changeOrigin": true,
        "secure": false,
        "pathRewrite": {
          "^/api": ""
        }
      },
      "/api/v1": {
        "target": "http://api-dev..com/v1",
        "logLevel": "debug",
        "changeOrigin": true,
        "secure": false,
        "pathRewrite": {
          "^/api/v1": ""
        }
      },
      "/api/common/v1": {
        "target": "http://api-dev..com/api/common/v1",
        "logLevel": "debug",
        "changeOrigin": true,
        "secure": false,
        "pathRewrite": {
          "^/api/common/v1": ""
        }
      }
    }
    

    调用接口:

    const url = "http://localhost:4200/api/common/v1/xxxx"
    //在调用的时候请求会被代理到:http://api-dev..com/api/common/v1/xxxx
    this.http.get(url)   .then(response => {
      //逻辑处理
    }).catch(error=>{
     //逻辑处理
    });
    

    package.json 配置:

    "start":  "ng serve --host 0.0.0.0  --proxy-config proxy.config.json ",
    

    运行代码:

    npm run start
    

    扩展 - 环境配置

    environments 文件夹下创建environment.local.ts文件:

    export const environment = {
      production: false,
      BASE_COMMON_URL:"http://localhost:4200/api/common/v1",
      BASE_URL:"http://localhost:4200/api/v1",
      BASE_API:"http://localhost:4200/api",
    };
    

    angular.json配置

    {
      ...//省略
      "projects": {
        "your-project-name": {
          ...//省略
          "architect": {
            "build": {
              ...//省略
              "configurations": {
                "production": {
                      ...//省略
                  },
                "local": {//增加代码
                  "fileReplacements": [
                    {
                      "replace": "src/environments/environment.ts",
                      "with": "src/environments/environment.local.ts"
                    }
                  ]
                }
              }
            },
            "serve": {
              ...//省略
              "configurations": {
                "production": {
                  "browserTarget": "new-m2-frontend:build:production"
                },
                "local": {//增加代码
                  "browserTarget": "your-product-name:build:local"
                }
              }
            },
          ...//省略
    }
    
    

    package.json

     "proxy":  "ng serve --host 0.0.0.0  --proxy-config proxy.config.json --configuration=local",
    

    运行代码:

    npm run proxy
    

    这样你的修改对其他人的影响就降到最低了

    相关文章

      网友评论

          本文标题:angular proxy 配置

          本文链接:https://www.haomeiwen.com/subject/ejaejrtx.html