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

相关内容

热门资讯

一秒答解!hhpoker辅助器... 一秒答解!hhpoker辅助器(辅助挂)真是真的是有挂(有挂规律)1、hhpoker辅助器免费脚本咨...
最新技巧!德州透视是真的吗(辅... 最新技巧!德州透视是真的吗(辅助挂)好像是真的有挂(了解有挂)所有人都在同一条线上,像星星一样排成一...
查到实测辅助!hhpkoer辅... 查到实测辅助!hhpkoer辅助挂是真的吗(辅助挂)竟然是有挂(有挂实锤)hhpkoer辅助挂是真的...
免费测试版!德州局怎么透视(辅... 免费测试版!德州局怎么透视(辅助挂)一直真的有挂(真实有挂)1、玩家可以在德州局怎么透视透视最简单三...
玩家必备教程!购买wepoke... 玩家必备教程!购买wepoker模拟器(辅助挂)好像是有挂(果真有挂)1、购买wepoker模拟器有...
最新技巧!竞技联盟透视插件(辅... 最新技巧!竞技联盟透视插件(辅助挂)好像是有挂(有挂方针)1、下载好竞技联盟透视插件脚本下载之后点击...
盘点一款!hhpoker一直输... 盘点一款!hhpoker一直输有挂吗(辅助挂)都是有挂(真实有挂)1、hhpoker一直输有挂吗破解...
六分钟了解!aapoker安装... 六分钟了解!aapoker安装包怎么使用(辅助挂)确实是真的有挂(有挂工具)小薇(辅助器软件下载)致...
科普常识!佛手在线大菠萝辅助(... 科普常识!佛手在线大菠萝辅助(辅助挂)原来真的有挂(有挂方式)小薇(辅助器软件下载)致您一封信;亲爱...
教程辅助!wpk辅助软件(辅助... 教程辅助!wpk辅助软件(辅助挂)切实存在有挂(有挂教学)wpk辅助软件脚本下载中分为三种模型:wp...