Angular代理配置以更改URL

时间:2018-08-21 18:20:20

标签: angular proxy

目标是使用代理更改URL:

  1. /mock/service/getInfo ----> www.example.com/service/getInfo
  2. /mock/service/submit ----> www.example.com/service/submit-test

因此,除了添加目标外,在第一个调用中,我们删除了mock,在第二个url中,我们删除了mock,最后添加了-test

第一个网址没有问题,但不了解如何为第二个网址编写配置

配置:

const PROXY_CONFIG = [{
 context: [
    "/mock"
 ],
 target: "https://www.example.com",
 pathRewrite: {
    '^/mock' : '', 
    '^/submit' : '/submit-test'
 },
 secure: false,
 changeOrigin: true,
 logLevel: "debug"
}]
module.exports = PROXY_CONFIG;

1 个答案:

答案 0 :(得分:0)

按如下所示更改proxy.config。并创建一个名为'proxy.config.json'的.json文件

{
    "/mock/service/getInfo/": {
         target: "https://www.example.com",
         pathRewrite: {
            '/mock' : ''
         },
         secure: false,
         changeOrigin: true,
         logLevel: "debug"
    },
    "/mock/service/submit/": {
         target: "https://www.example.com",
         pathRewrite: {
            '/mock/service/submit' : '/service/submit-test'
         },
         secure: false,
         changeOrigin: true,
         logLevel: "debug"
    }
}

然后在package.json中添加了一个新参数

{
  "name": "example-angular-app",
  "version": "0.0.2",
  "license": "MIT",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config=proxy.conf.json",
    "start-prod": "ng serve --proxy-config=proxy.conf.json --prod",
    "start-prod-sm": "ng serve --proxy-config=proxy.conf.json --prod --sourcemaps",
    "build": "ng build",
    "build-prod": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
        ...
  },
  "devDependencies": {
        ...
  }
}

您可以使用“ npm run start ”命令来运行Angular应用程序。