Use Angular proxy to solve front-end cross-domain problems

There are two options for bypassing CORS restrictions in the front-end portion of an Angular application: (1) JSONP and (2) Angular proxies.

Among them, JSONP cannot set header information, so if you need to set header information, you can use Angular proxy.

The proxy.conf.json file is a configuration file in the Angular application to configure the proxy server. Its main role is to help front-end developers solve cross-origin resource sharing (Cross-Origin Resource Sharing, CORS) problems during the development and debugging phases.

In modern web applications, to improve security, browsers enforce the same-origin policy, which restricts resources loaded from one origin from interacting with another. This limitation may cause front-end developers to encounter cross-domain issues during development, especially when the front-end part of the application is on a different domain name or port than the back-end API part.

The proxy.conf.json file configures the proxy server, allowing developers to solve cross-domain problems by sending requests to the proxy server during the development process. This file is usually located in the root directory of the Angular project.

The basic structure of the proxy.conf.json file is a JSON object that can contain multiple proxy configuration items. Each proxy configuration item consists of a path matching rule and a target URL. When an application sends a request to a URL that matches a path rule, the proxy server forwards the request to the target URL and returns the response to the application.

The following is an example structure of a proxy.conf.json file:

{
    
    
  "/api/*": {
    
    
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel": "debug"
  },
  "/images/*": {
    
    
    "target": "http://localhost:4000",
    "secure": false,
    "logLevel": "debug"
  }
}

In the above example, there are two proxy configuration items. The first configuration item specifies that /api/*requests matching the path will be forwarded to http://localhost:3000. The second configuration item specifies that /images/*requests matching the path will be forwarded to http://localhost:4000.

Key properties of the proxy.conf.json file include:

  • target: Specify the target URL to forward the request to. It can be a full URL including protocol, host and port, or a relative path.
  • secure: Specifies whether to enable the secure HTTP protocol (HTTPS).
  • logLevel: Specifies the log level, which is used to output the log information of the proxy server.

In order to use the proxy.conf.json file during development, you can start the development server through the Angular CLI command and associate it with the proxy.conf.json file. For example, the following command can be used to start the development server:

ng serve --proxy-config proxy.conf.json

In this way, the development server will process the proxy request according to the configuration items in the proxy.conf.json file, and forward the corresponding request to the target URL.

By using the proxy.conf.json file to configure the proxy server, front-end developers can easily resolve cross-domain issues during the development and debugging stages, enabling front-end applications to interact with back-end APIs.

The way to use proxy in Angular is as follows.

  1. First create a proxy.conf.jsonfile .
{
    
    
  "/api": {
    
    
    "target": "https://www.m22.com", // example endpoint
    "secure": true,
    "pathRewrite": {
    
    
      "^/api": "/kats" // rewrites the endpoint path from '/api' to '/kats'
    },
    "changeOrigin": true
  }
}
  1. In the serve area of ​​the angular.json file, add the configuration file defined in the previous step:
 "serve": {
    
    
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
    
    
            "browserTarget": "move-safe:build",
            "proxyConfig": "src/proxy.conf.json" // location of the config file
          },

Finally invoke the HTTP request:

getAll(): Observable<KatsResponse> {
    
    
    const url = '/api/?show=option1'; 
    // request will be sent to "https://www.m22.com/kats?show=option1"
    const headers = new HttpHeaders({
    
    
      'Content-Type': 'application/json',
    });

    return this.http
      .get<KatsResponse>(url, {
    
     headers })
      .pipe();
  }

Guess you like

Origin blog.csdn.net/i042416/article/details/130702801