代理无法解决angular 8中的CORS错误

问题描述

我遇到了错误

Access to XMLHttpRequest at 'https://samples.openweathermap.org/data/2.5/group?id=1248991,1850147,2644210,2988507,2147714,4930956,1796236,3143244&units=metric&appid=ab8514a074b0dbbe71a9626926b82bf9' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

现在有一段时间,我进行了一些挖掘,发现使用启用了cos的代理可以解决此问题,但是由于某些原因,它对我不起作用。

这是我从中调用请求的方法

 getWeather(city: string[],appid: string) {
   this.http.get(
  `https://samples.openweathermap.org/data/2.5/group?id=${city}&units=metric&appid=${appid}`)
  .subscribe((data) => {
    console.log(data);
  },(err) => {
    console.log(err);
  });
}

这是我在src文件夹中创建的proxy.conf.json

{
"/api/*": {
    "target": "http://localhost:3000","secure": false
    
}
}

并且我已经将行"proxyConfig": "src/proxy.conf.json"添加到我的angular.json中的architect> serve> options

没有编译错误,为什么我仍然收到此错误

解决方法

实际上,您的代理什么都不做,要使其正常工作,您需要这样做

environment.ts中添加apiUrl并将值设置为/api

environment.prod.ts中添加apiUrl并将值设置为https://samples.openweathermap.org

 getWeather(city: string[],appid: string) {
   this.http.get(
  `${environment.apiUrl}/data/2.5/group?id=${city}&units=metric&appid=${appid}`)
  .subscribe((data) => {
    console.log(data);
  },(err) => {
    console.log(err);
  });
}

然后在您的代理服务器中

{
 "/api/*": {
    "target": "https://samples.openweathermap.org/","secure": true,"logLevel": "debug"
    "changeOrigin": true,"pathRewrite": {
        "^/api/": ""
    },}
}

执行此操作时,您的http get将会调用/api/data/2.5/group?id=xxx&units=metric&appid=yyy

然后代理发现有人正在调用以/api开头的内容,然后由于pathRewrite,它将删除/api/并将其替换为https://samples.openweathermap.org/

然后,最终网址将为https://samples.openweathermap.org/data/2.5/group?id=xxx&units=metric&appid=yyy

请注意,如果您看到“网络”标签,则会看到网址为localhost:4200,这是代理如何避免CORS的方式