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可以开... 透视玄学!wepoker可以开透视吗(透视)其实是真的有挂(详细辅助规律教程)软件透明挂微扑克wpk...
透视软件!淘宝买wepoker... 透视软件!淘宝买wepoker透视有用吗(透视)本来真的是有挂(详细辅助专业教程);暗藏猫腻,小编详...
透视玄学!hh poker软件... 透视玄学!hh poker软件(透视)真是真的是有挂(详细辅助实用技巧);1、系统规律教程、辅助透视...
透视科技!大菠萝789辅助器下... 透视科技!大菠萝789辅助器下载(透视)一贯存在有挂(详细辅助安装教程)1、玩家可以在软件透明挂俱乐...
透视工具!pokerrrr2辅... 透视工具!pokerrrr2辅助(透视)原来真的是有挂(详细辅助力荐教程)1、不需要AI权限,帮助你...
透视脚本!pokemmo手机版... 透视脚本!pokemmo手机版脚本免费(透视)果然存在有挂(详细辅助线上教程);1、系统规律教程、辅...
透视教学!wpk俱乐部辅助器(... 透视教学!wpk俱乐部辅助器(透视)切实真的有挂(详细辅助黑科技教程);1、该软件可以轻松地帮助玩家...
透视辅助!wepoker透视有... 透视辅助!wepoker透视有没有(透视)其实真的有挂(详细辅助新版2025教程)亲,关键说明,we...
透视总结!哈糖大菠萝有挂吗(透... 透视总结!哈糖大菠萝有挂吗(透视)切实是真的有挂(详细辅助细节方法)辅助器中分为三种模型:软件透明挂...
辅助透视!wpk私人辅助(透视... 辅助透视!wpk私人辅助(透视)切实是有挂(详细辅助切实教程)1、系统规律教程、辅助透视等服务,为用...