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

最近玩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
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值