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插... 您好,这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在这款游戏中打...
分享认知!wepoker轻量版... 分享认知!wepoker轻量版有透视吗,德普之星有透视辅助吗,确实真的有挂(真的有挂)1、透视辅助软...
六分钟了解!德扑圈透视,wep... 六分钟了解!德扑圈透视,wepoker辅助器安装包定制,都是是真的有挂(有挂细节)一、wepoker...
大家学习交流!wepoker插... 大家学习交流!wepoker插件辅助,竞技联盟破解版最新版,原来存在有挂(有挂攻略)1、玩家可以在线...
技术分享!hhpoker德州机... 技术分享!hhpoker德州机器人,aapoker辅助怎么用,总是有挂(有挂攻略)1、每一步都需要思...
一分钟了解!竞技联盟透视,hh... 一分钟了解!竞技联盟透视,hhpoker怎么开透视,好像存在有挂(有挂细节)一、游戏安装教程牌型概率...
玩家必备教程!sohoo po... 玩家必备教程!sohoo poker辅助,hhpoker作弊码怎么用,确实真的是有挂(有挂详情)一、...
热点推荐!哈糖大菠萝攻略,红龙... 热点推荐!哈糖大菠萝攻略,红龙poker作弊指令,果然真的有挂(有挂存在)1、免费脚本咨询教程、免费...
指导大家!pokermaste... 指导大家!pokermaster脚本,德普辅助app,本来是真的有挂(有挂方法)1、完成辅助器v3....
科技通报!aapoker透视怎... 科技通报!aapoker透视怎么用,wejoker私人辅助软件,都是真的有挂(有挂攻略)1、这是跨平...