DEV Community 👩‍💻👨‍💻

John Peters
John Peters

Posted on • Updated on

Angular HTTP Proxy (CORS) in 10 minutes

With Client Side Proxies you can easily redirect cross domain url requests!

  • First create a proxy.conf.json file in root directory.
{
  "/g": {
    "target": "https://www.google.com",
    "secure": false,
    "pathRewrite": {
      "^/g": ""
    },
    "changeOrigin": true
  }
}
Enter fullscreen mode Exit fullscreen mode

So if the url is http://localhost/g

 The g becomes https://google.com

Enter fullscreen mode Exit fullscreen mode
  • Set up the Angular.json config. to use the proxy.
     "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "TESTING:build",
            // this line here.
            "proxyConfig": "proxy.conf.json"
          },
        ...
Enter fullscreen mode Exit fullscreen mode

Results

Alt Text

Note

This does not work on an http client get like this:

 // beacuse there's no listener on port 4200
 http.get("localhost:4200/g")

Enter fullscreen mode Exit fullscreen mode

This shows what client side routing does; which is, parse a URL in the browser, and route to proper component. Client side Routing does not imply an endpoint, it's just an entry to another page.

Server side routing does imply endpoints that are highly strict about what they do. Instead of serving a page (which they can do statically) they mostly serve data.

The proxy is an easy way around CORS issues, but will soon need a bit more regarding same-site policy implementation.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.