A Guide to Configuring Proxies to Prevent CORS Issues in Angular

3 분 소요

When integrating third-party APIs during frontend development, one of the most common errors encountered in the local development environment is the CORS (Cross-Origin Resource Sharing) error. To ensure smooth API integration testing, a logical and definitive approach is required to bypass this issue locally.

1. What is CORS, and why does it occur?

CORS is a security mechanism enforced by web browsers when an application attempts to request resources from a domain different from the one currently running. For instance, if your web application is served on localhost:4200 but makes an HTTP request to http://third-party-example.com, the browser sends a preflight request (HTTP OPTIONS) before the actual request. This preflight checks if the target server permits access from localhost. If the server does not return the appropriate Access-Control-Allow-Origin header, the browser blocks the response for security reasons.

The critical point to understand is that only web browsers enforce CORS policies. This explains why making the exact same request via Postman or Node.js environments works perfectly fine, whereas it fails exclusively within the browser environment.

2. Solution Methodology: Angular CLI Proxy

Since CORS occurs because the browser directly requests a cross-origin domain, the problem can be solved by configuring a non-browser environment (Node.js) to make the request on its behalf. Angular natively provides a Node.js-based proxy feature within its development server (ng serve).

By using this proxy, the browser sends the request to the proxy on localhost rather than the external domain. The proxy intercepts this request and forwards it to the external API. Because the origin of the outgoing request to the target server is now the Node.js proxy and not the browser, the browser’s CORS policy check is completely bypassed.

1. Creating the proxy.conf.json file

First, create a proxy.conf.json file under the src/ directory of your project. This file defines the routing rules, specifying which incoming paths should be intercepted and where they should be forwarded.

{
  "/api": {
    "target": "http://third-party-example.com",
    "secure": false
  }
}
  • /api: Instructs the proxy to intercept any request originating from the app that starts with localhost:4200/api.
  • target: The destination server URL where the actual request should be forwarded.
  • secure: Setting this to false allows the proxy to ignore certificate errors and proceed if the target uses HTTPS with an invalid SSL certificate.

2. Applying the configuration to angular.json

Now that the routing rules are defined, the Angular development server must be configured to recognize this file upon startup. Open the angular.json file at the root of your project and add the proxyConfig property to the options object of the serve target.

{
  "projects": {
    "my-app": {
      "architect": {
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "proxyConfig": "src/proxy.conf.json"
          }
        }
      }
    }
  }
}

Restart ng serve to apply the changes. From now on, when your application makes a request to http://localhost:4200/api/users, the built-in proxy will safely route it to http://third-party-example.com/api/users.

Conclusion and Considerations

The Angular proxy feature is strictly a development-only tool designed for the local dev server (ng serve). While it efficiently resolves bottlenecks during development, it is crucial to remember that this configuration is not included when the application is built and deployed to a production environment.

For a fundamental resolution in the actual production environment, you must implement one of the following approaches:

  • Request the external server or API provider to explicitly add your production domain to their CORS allowlist (Access-Control-Allow-Origin).
  • Implement an architecture where the client does not directly call the external API. Instead, the client sends requests to your backend server, which then makes the call to the external API and returns the result (e.g., a BFF pattern).

References

How to use a proxy to prevent CORS issues with Angular

한국어(Korean) Page

태그:

카테고리:

업데이트:

댓글남기기