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

相关内容

热门资讯

科普攻略!aapoker辅助怎... 科普攻略!aapoker辅助怎么用,hhpoker有后台操作吗,安装教程(有挂技巧)1、点击下载安装...
玩家必看教程!竞技联盟破解版最... 玩家必看教程!竞技联盟破解版最新版,云扑克有透视吗,技巧教程(有挂辅助)这是由厦门游乐互动科技有限公...
信息共享!wepoker怎么设... 1、信息共享!wepoker怎么设置房间,wepoker辅助真的假的,揭秘教程(有挂攻略);详细教程...
教程辅助!hhpoker是正规... 教程辅助!hhpoker是正规的吗,约局吧怎么看有没有挂,技巧教程(有挂透明);实战中需综合运用上述...
一分钟快速了解!哈糖大菠萝有挂... 《一分钟快速了解!哈糖大菠萝有挂吗5个常用方法,agpoker辅助,2025版教程(有挂技巧)》 哈...
玩家攻略推荐!智星德州有脚本吗... 玩家攻略推荐!智星德州有脚本吗,wepoker透视脚本安卓,技巧教程(有挂软件);实战中需综合运用上...
终于知道!werplan外挂,... 终于知道!werplan外挂,wepoker可以透视码,wepoke教程(有挂技巧)1、不需要AI权...
程序员教你!pokemmo脚本... 程序员教你!pokemmo脚本辅助器,德州局透视,wpk教程(有挂技巧)这是由厦门游乐互动科技有限公...
新手必备!德普之星辅助工具如何... 新手必备!德普之星辅助工具如何打开,wepoker提高好牌率,技巧教程(有挂技巧);亲真的是有正版授...
必看攻略!pokemmo手机脚... 《必看攻略!pokemmo手机脚本,wepoker怎么拿到好牌,力荐教程(有挂技巧)》 wepoke...