Home >Web Front-end >JS Tutorial >A brief analysis of how to use Api proxy in Angular

A brief analysis of how to use Api proxy in Angular

青灯夜游
青灯夜游forward
2022-04-18 10:54:072475browse

This article will introduce to you how to use Api proxy in Angular, and talk about using angualr to explain the topic of proxy api docking. I hope it will be helpful to everyone!

A brief analysis of how to use Api proxy in Angular

As a front-end developer, we often interface with the back-end. However, we always encounter cross-domain problems during the docking process. So how do we What's the solution?

This article uses angualr to explain the topic of agent api docking. [Related tutorial recommendations: "angular tutorial"]

First of all, let's understand what cross-domain is.

Cross-domain

Simple understanding: When a request is made, the protocol, domain name (ip address), portThree partsThe difference between any current page’s url is cross-domain.

Take my site https://jimmyarea.com as an example:

Requested address Whether it is cross-domain Reason
jimmyarea.com Yes The protocols are different
jimmyarea.cn is a different address from
https://127.0.0.1:9000 Yes The address and port number are different

##Agent

At this time, we can use the proxy to locally jointly debug the

api addresses of different environments.

First, we create a new file

proxy.conf.json in the root directory of the project.

We take the interface request

https://jimmyarea.com/api/public/article?page=-1 as an example:

{
  "/api": {
    "target": "https://jimmyarea.com/",
    "changeOrigin": true,
    "secure": false,
    "pathRewrite": {
      "^/api": "/api"
    }
  }
}

target is the address of the proxy, pathRewrite is the rewrite of the prefix of the proxy.

After completing the proxy file, you need to enable the proxy. We add one more command line in

package.json, indicating that it is used for debugging in the development environment.

"script": {
  "dev": "ng serve --proxy-config=proxy.conf.json",
}

Execute

npm run dev Start the project and bring the agent. Every time the proxy file changes, you need to restart the command line~

Verification

We create a new

article Service, where the article.service.ts file content is as follows:

import { Injectable } from '@angular/core';
// http 客户端
import { HttpClient } from '@angular/common/http'

@Injectable({
  providedIn: 'root'
})

export class ArticleService {

  constructor(
    private http: HttpClient
  ) { }
   
  // 获取文章列表
  getArticleList() {
    return this.http.get('/api/public/article', {
      // 返回类型
      responseType: 'json',
      // 请求的参数
      params: {
        page: -1
      }
    })
  }

}

The above request, the address on the page is

http://localhost:4200/api/public/article ?page=-1, actually accessing the address https://jimmyarea.com/api/public/article?page=-1. We can call and verify it in user-list.component.ts:

ngOnInit():void {
  this.articleService.getArticleList().subscribe({
    next: (data: any) => {
      console.log(data)
    },
    error: () => {}
  })
  // ...
}

After the program runs, you can see the following network request on the console:

A brief analysis of how to use Api proxy in Angular

Good Job, Bro. We can perfectly proxy the address given by the backend and debug it, and the proxy can proxy more than one address. Readers can write multiple proxy addresses to verify~

[End]

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of A brief analysis of how to use Api proxy in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete