Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use angular-cli with multiple path proxy matching

How can I define multiple paths to proxy in my proxy.conf.json? The angular-cli proxy documentation on github looks like you can only have one path (/api):

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false
  }
}

But when I look into the webpack proxy or the http-proxy-middleware documentation, I see it should be possible to define multiple paths (/api-v1 and /api-v2):

// Multiple entry
proxy: [
  {
    context: ['/api-v1/**', '/api-v2/**'],
    target: 'https://other-server.example.com',
    secure: false
  }
]

But I don't understand how I can get this into the proxy.conf.json.

like image 346
Hans Avatar asked Jun 12 '17 07:06

Hans


2 Answers

Use the following syntax in your proxy.conf.json:

[
  {
    "context": ["/api-v1/**", "/api-v2/**"],
    "target": "https://other-server.example.com",
    "secure": false
  }
]

Actual syntax that works is as below:

[
    {
        "context": [
            "/api",
            "/other-uri"
        ],
        "target": "http://localhost:8080",
        "secure": false
    }
]
like image 172
Hans Avatar answered Nov 11 '22 00:11

Hans


The syntax for multiple entries (using context) is documented here: https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md#multiple-entries

const PROXY_CONFIG = [
    {
        context: [
            "/my",
            "/many",
            "/endpoints",
            "/i",
            "/need",
            "/to",
            "/proxy"
        ],
        target: "http://localhost:3000",
        secure: false
    }
]

module.exports = PROXY_CONFIG;

This also requires that you rename your config from .json to .js and point your run command at the new file.

For me the context syntax doesn't quite work (I assume because I want to use wildcards). So I came up with the following solution which allows you to generate a config:

module.exports = [
  "/my",
  "/many",
  "/endpoints",
  "/i",
  "/need",
  "/to",
  "/proxy",
  "/folder/*"
].reduce(function (config, src) {
  config[src] = {
    "target": "http://localhost:3000",
    "secure": false
  };
  return config;
}, {});

This got the job done for me. (note that this still requires that your rename your proxy.conf.json to proxy.conf.js and edit your run command to point at the renamed file)

like image 4
Martin Avatar answered Nov 11 '22 01:11

Martin