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

相关内容

热门资讯

推荐一款!微乐如何自己建脚本(... 推荐一款!微乐如何自己建脚本(作弊器),微乐龙江填大坑本来是有透视挂插件1、玩家可以在微乐如何自己建...
热点推荐!微信小程序游戏辅助器... 热点推荐!微信小程序游戏辅助器(辅助器),微乐辽宁斗地主原来是有透视挂技巧亲,关键说明,微信小程序游...
必备辅助推荐!微乐自建房辅助工... 必备辅助推荐!微乐自建房辅助工具官网(作弊器),微乐家乡麻将一贯存在有透视挂教程微乐自建房辅助工具官...
玩家必备教程!微乐自建房辅助可... 玩家必备教程!微乐自建房辅助可信吗(透视挂),微乐河池麻将果然存在有透视挂工具1、首先打开微乐自建房...
热门推荐!微乐小程序插件免费(... 热门推荐!微乐小程序插件免费(透视器),微乐安徽麻将一直是有透视挂app在进入微乐小程序插件免费软件...
实测揭晓!微信小程序微乐辅助器... 实测揭晓!微信小程序微乐辅助器破解版(开挂),微乐提坑竟然有透视挂脚本1、超多福利:超高返利,海量正...
必备辅助推荐!微乐家乡破解版(... 必备辅助推荐!微乐家乡破解版(开挂),微乐长春麻将本来真的是有透视挂软件1、这是跨平台的微乐家乡破解...
程序员教你!微乐广西麻辣(作弊... 程序员教你!微乐广西麻辣(作弊器),微乐长沙跑胡子都是真的是有透视挂攻略微乐广西麻辣透视方法中分为三...
一分钟快速了解!小程序微乐斗地... 一分钟快速了解!小程序微乐斗地主辅助(透视挂),微乐保皇一直真的是有透视挂方法1)小程序微乐斗地主辅...
重大消息!微乐家乡游戏攻略(透... 重大消息!微乐家乡游戏攻略(透视挂),陕西微乐三代切实是有透视挂软件1、微乐家乡游戏攻略脚本辅助下载...