Angular应用在Chrome浏览器中出现CORS错误
创始人
2024-10-30 16:00:18
0

使用代理服务器在Angular应用和服务器之间进行通信。可以使用Angular中的HttpClient和HttpInterceptor实现代理服务器。例如:

  1. 安装http-proxy-middleware: npm install http-proxy-middleware --save

  2. 在src目录下创建一个名为proxy.conf.json的文件,将下列代码复制到文件中:

{ "/api": { "target": "http://", "secure": false } }

  1. 在src/app目录下创建一个名为http.interceptor.ts的文件,将以下代码复制到文件中:

import { Injectable } from '@angular/core'; import { HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';

@Injectable() export class HttpInterceptorService implements HttpInterceptor { intercept(req: HttpRequest, next: HttpHandler) { const apiReq = req.clone({ url: http://localhost:4200/${req.url} }); return next.handle(apiReq); } }

  1. 在app.module.ts文件中,将HttpClientModule和HttpInterceptorService添加到imports和providers数组中。

import { HttpClientModule } from '@angular/common/http'; import { HttpInterceptorService } from './http.interceptor';

@NgModule({ ... imports: [ ... HttpClientModule ], providers: [ ... HttpInterceptorService, { provide: HTTP_INTERCEPTORS, useClass: HttpInterceptorService, multi: true } ], ... })

  1. 使用HttpClient请求数据时,在请求URL前添加路径“/api”,例如:

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错误。

相关内容

热门资讯

热点讨论!杭州都莱大菠萝辅助器... 【福星临门,好运相随】;热点讨论!杭州都莱大菠萝辅助器,wepoker怎么看牌型,必胜教程(有挂工具...
我来教大家!九游辅助真的假的,... 我来教大家!九游辅助真的假的,wepoker辅助器是真的吗,插件教程(有挂规律);我来教大家!九游辅...
热点讨论!多乐找刺激辅助,aa... 您好,多乐找刺激辅助这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这...
玩家必备教程!开心泉州小程序工... 玩家必备教程!开心泉州小程序工具,xpoker辅助控制,扑克教程(存在有挂);开心泉州小程序工具软件...
重大科普!欢乐达人暗堡辅助,德... 重大科普!欢乐达人暗堡辅助,德州局怎么透视,分享教程(有挂头条);亲,有的,ai轻松简单,又可以获得...
我来教教大家!hhpoker大... 【福星临门,好运相随】;我来教教大家!hhpoker大菠萝有没有作比,wepoker免费脚本咨询,总...
盘点一款!微信小程序透视挂,w... 盘点一款!微信小程序透视挂,wepoker黑侠辅助器,2025新版技巧(有挂攻略)是一款可以让一直输...
信息共享!开心泉州小程序辅助器... 信息共享!开心泉州小程序辅助器,wpk辅助哪里买,必胜教程(有挂工具)是一款可以让一直输的玩家,快速...
教程辅助!点我休闲辅助器,we... 教程辅助!点我休闲辅助器,wepoker轻量版辅助,黑科技教程(确实有挂)是一款可以让一直输的玩家,...
玩家必看科普!h5大厅反杀,w... 玩家必看科普!h5大厅反杀,wejoker辅助软件,科技教程(有挂规律);h5大厅反杀辅助器中分为三...