angular 使用前端代理方式实现请求跨域,解决代理不生效问题!!

本文详细介绍了一种在Angular项目中实现跨域请求的方法。通过在项目根目录下定义并配置proxy.config.json文件,以及修改angular.json文件,实现了将本地请求反向代理到目标服务器。文章还提供了具体的代码示例和服务调用方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近玩angular,在使用代理方式进行前端跨域处理时,一直无法代理成功,查了许多资料,发现所有angular跨域教程都不完整,下边为大家奉上完整版的跨域操作:

1.在项目根目录下定义proxy.config.json文件

2.在第1步刚刚创建好的proxy.config.json中写入以下内容进行跨域配置:

以下 的配置实现了将:http://localhost:4200/api-weather  反向代理为:http://t.weather.sojson.com

{
  "/api-weather": {    //需要代理的请求: http://localhost:4200/api-weather
    "target": "http://t.weather.sojson.com",//反向代理到target,请求变成:http://t.weather.sojson.com/api-weather
    "logLevel": "debug", //打印代理过程
    "changeOrigin": true,
    "secure": false,
    "pathRewrite": {
        "^/api-weather": ""  //将/api-weather替换为空,新的请求变成:http://t.weather.sojson.com
    }
  }

}

3.*配置根目录下的angular.json,这一步最重要!!网上的教程都没有

在其中的serve.options加入配置:"proxyConfig": "proxy.config.json"

4.测试,定义weather.service.ts,发送请求

import { Injectable } from '@angular/core';
import { HttpClient ,HttpHeaders} from '@angular/common/http';
import { Weather } from '../pages/weather/weather';
import { Observable ,of} from 'rxjs';


const httpOptions = {
  headers: new HttpHeaders({
    'Access-Control-Allow-Origin': '*'
  })
};


@Injectable()
export class WeatherService {
  constructor(private http: HttpClient) {
  }
  fetchData(params:any):Observable<Weather>{
    let url = "/api-weather/api/weather/city" //请求会被反向代理到http://t.weather.sojson.com/api/weather/city
    let urlTemp = url+"/"+params.cityId //params.cityId="101270101"
    return this.http.get<Weather>(urlTemp);
  };

}

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值