As a front-end developer, we frequently interface with the back-end. However, we always encounter cross-domain problems during the docking process, so how do we solve them?
This article uses angualr
to explain the topic of agent api
docking. [Recommended related tutorials: "Angular Tutorial"]
First, let's understand what cross-domain is.
A simple understanding ofcross-domain
: When url
of任意一个
the three parts of协议、域名(ip地址)、端口
of a request and the current page is different, it is cross-domain .
Take my site https://jimmyarea.com
as an example:
Is | the requested address | cross-domain? |
---|---|---|
jimmyarea.com | has | a different protocol. |
jimmyarea.cn | has | a different address. |
https://127.0.0.1:9000 | has | a different address and port number | .
The proxy
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 agent, pathRewrite
is the rewriting of the prefix of the agent.
After completing the proxy file, you need to enable the proxy. We add one more command line to 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
to start the project and bring the agent. Every time the proxy file changes, you need to restart the command line
to verify that
we have created a new article
service. The content of the article.service.ts
file is as follows:
import { Injectable } from '@angular/core'; // http client import { HttpClient } from '@angular/common/http' @Injectable({ providedIn: 'root' }) export class ArticleService { constructor( private http: HttpClient ) { } // Get the article list getArticleList() { return this.http.get('/api/public/article', { //Return type responseType: 'json', //Request parameters params: { page: -1 } }) } }
For the above request, the address on the page is http://localhost:4200/api/public/article?page=-1
. In fact, the address accessed is https://jimmyarea.com/api/public/article?page=-1
. We can verify it by calling 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 requests on the console:
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]