最近玩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);
};
}