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、外挂技法!大菠萝免费辅助器...
外挂模块!uupoker透视,... 外挂模块!uupoker透视,werplan外卦神器-一贯一直都是有辅助教程(哔哩哔哩)在进入wer...
外挂妙招!红龙poker有辅助... 外挂妙招!红龙poker有辅助吗,红龙poker作必弊指令-果然是有辅助app(哔哩哔哩)1、红龙p...
外挂模板!大菠萝手游辅助,佛手... 外挂模板!大菠萝手游辅助,佛手在线大菠萝技巧-切实真的有辅助攻略(哔哩哔哩)佛手在线大菠萝技巧辅助器...
外挂资料!哈糖大菠萝有没有挂,... 外挂资料!哈糖大菠萝有没有挂,哈糖大菠萝能开挂吗-确实是有辅助插件(哔哩哔哩)1、哈糖大菠萝能开挂吗...
外挂操作!拱趴大菠萝自动计算机... 外挂操作!拱趴大菠萝自动计算机器人,德普之星怎么开辅助-竟然真的有辅助脚本(哔哩哔哩)1.拱趴大菠萝...
外挂教材!wepoker安装教... 外挂教材!wepoker安装教程,哈糖大菠萝有没有挂-原来真的是有辅助插件(哔哩哔哩)该软件可以轻松...
外挂法子!智星菠萝德州插件最新... 外挂法子!智星菠萝德州插件最新版本更新内容详解,德普之星透视辅助软件-原来真的是有辅助软件(哔哩哔哩...
外挂演示!sohoo poke... 外挂演示!sohoo poker辅助,werplan外卦神器-一直真的有辅助软件(哔哩哔哩)1、we...