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

相关内容

热门资讯

今日百科!约局吧开挂,hhpo... 《今日百科!约局吧开挂,hhpoker辅助,扑克教程(有挂方法)》 约局吧开挂软件透明挂更新公告新增...
玩家实测!wepoker私人局... 玩家实测!wepoker私人局透视,hhpoker有后台操控吗,AI教程(有挂教程);hhpoker...
科技新动态!hhpoker真能... 科技新动态!hhpoker真能买到挂吗,wepoker正确养号方法,曝光教程(有挂透明);hhpok...
分辨真假!拱趴大菠萝万能挂图解... 分辨真假!拱趴大菠萝万能挂图解,wpk作弊,揭秘攻略(有挂透明);大神普及一款德州ai内幕,确定了拱...
科技介绍!德普之星辅助器怎么用... 科技介绍!德普之星辅助器怎么用,约局吧开挂,细节揭秘(有挂透明);原来确实真的有挂(需添加指定薇13...
一分钟秒懂!拱趴大菠萝挂怎么安... 一分钟秒懂!拱趴大菠萝挂怎么安装,约局吧德州透视,必胜教程(有挂方法)关于拱趴大菠萝挂怎么安装机制的...
终于清楚!红龙poker有辅助... 终于清楚!红龙poker有辅助吗,aapoker公共底牌,揭秘攻略(有挂技巧)是一款可以让一直输的玩...
一分钟快速了解!aa poke... 一分钟快速了解!aa poker辅助包,pokemmo辅助脚本,技巧教程(有挂技巧)1、玩家可以在p...
查到实测辅助!哈糖大菠萝可以开... 查到实测辅助!哈糖大菠萝可以开挂吗,约局吧游戏挂,微扑克教程(有挂透视);哈糖大菠萝可以开挂吗软件透...
一分钟教你!We poker辅... 一分钟教你!We poker辅助器下载,hhpoker有作弊的吗,曝光教程(有挂攻略)1、点击下载安...