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

相关内容

热门资讯

透视详情"wepok... 透视详情"wepoker一直输的号能继续打吗"好像真的是有辅助软件(哔哩哔哩)wepoker一直输的...
透视揭露"aapok... 透视揭露"aapoker透视插件"竟然是真的辅助插件(哔哩哔哩)1)aapoker透视插件辅助插件:...
透视解迷"竞技联盟透... 透视解迷"竞技联盟透视插件"一直是真的辅助器(哔哩哔哩)1、竞技联盟透视插件有没有辅助教程、竞技联盟...
透视透视"竞技联盟辅... 透视透视"竞技联盟辅助插件"一贯真的有辅助app(哔哩哔哩)1、点击下载安装,竞技联盟辅助插件脚本分...
透视解迷"aapok... 透视解迷"aapoker破解侠是真的吗"都是是真的辅助脚本(哔哩哔哩)1、超多福利:超高返利,海量正...
透视教你"wepok... 透视教你"wepoker游戏的安装教程"果然存在有辅助方法(哔哩哔哩)小薇(辅助器软件下载)致您一封...
透视教你"we-po... 透视教你"we-poker辅助器"总是有辅助工具(哔哩哔哩)1、点击下载安装,we-poker辅助器...
透视详细"wepok... 透视详细"wepoker怎么看牌型"确实有辅助攻略(哔哩哔哩)1、玩家可以在wepoker怎么看牌型...
透视有挂"hhpok... 透视有挂"hhpoker真的假的"总是真的是有辅助攻略(哔哩哔哩)1、玩家可以在hhpoker真的假...
透视解迷"德普之星私... 透视解迷"德普之星私人局辅助免费"果然是有辅助教程(哔哩哔哩)1、玩家可以在德普之星私人局辅助免费透...