npm install http-proxy-middleware --save
{ "/api": { "target": "http://localhost:3000", "secure": false } }
这里我们把/api路径代理到http://localhost:3000
"scripts": { "start": "ng serve --proxy-config proxy.config.json" },
这些设置将通过--proxy-config选项来启动Angular应用程序,并将路径/api重定向到http://localhost:3000。
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' }) export class MyService { constructor(private http: HttpClient) {}
getData() { return this.http.get('/api/data'); } }
现在,当你调用getData()方法时,可以正常访问http://localhost:3000/api/data,而不需要担心跨域问题。