使用代理服务器在Angular应用和服务器之间进行通信。可以使用Angular中的HttpClient和HttpInterceptor实现代理服务器。例如:
安装http-proxy-middleware: npm install http-proxy-middleware --save
在src目录下创建一个名为proxy.conf.json的文件,将下列代码复制到文件中:
{
"/api": {
"target": "http://
import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
@Injectable()
export class HttpInterceptorService implements HttpInterceptor {
intercept(req: HttpRequesthttp://localhost:4200/${req.url}
});
return next.handle(apiReq);
}
}
import { HttpClientModule } from '@angular/common/http'; import { HttpInterceptorService } from './http.interceptor';
@NgModule({ ... imports: [ ... HttpClientModule ], providers: [ ... HttpInterceptorService, { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true } ], ... })
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http';
@Injectable({ providedIn: 'root' }) export class DataService { constructor(private http: HttpClient) {}
getMyData() { return this.http.get('/api/my-data'); } }
这样,在Chrome浏览器中将不会再看到CORS错误。