调用第 3 方时处理 CORS API

Handling CORS when calling 3rd party API

是的,这是一个非常有名的问题,我已经尝试了很多在之前的stack-overflow QnA中提到的方法,但是没有任何效果。我试图在我的应用程序中使用 BANZAI-Cloud API,但出现以下错误

这是我的服务代码class

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import { Observable } from 'rxjs';
import { HttpHeaders } from '@angular/common/http';

@Injectable({providedIn:"root"})
export class PriceTableService{
   
    private priceurl = "https://banzaicloud.com/cloudinfo/api/v1/providers/google/services/compute/regions/asia-east2/products"
    // private priceurl = "https://jsonplaceholder.typicode.com/posts"
    
    constructor(private http:HttpClient){}
    httpOptions = {
        headers: new HttpHeaders({
            'Access-Control-Allow-Methods':'DELETE, POST, GET, OPTIONS',
            'Access-Control-Allow-Headers':'Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With',
            'Content-Type':  'application/json',
            'Access-Control-Allow-Origin':'http://localhost:4200'
        })
      };
    getPrices(){
            this.http.get(this.priceurl,this.httpOptions).subscribe(result=>{
            console.log(result);
            return(result);
        })
     }
    ngOnInit() {
    }
}

这个API works in the POSTMAN and CHROME but cannot get data into my angular application , when I replace the URL with any other fake API我可以得到数据,但是上面提到的API没有给出数据,如果有人能帮我解决这个问题,那将是一个很大的帮助。

首先,您需要了解CORS检查是由浏览器完成的。这是一个 W3C 规范。任何扩展或工具(如 Postman)不受此约束。这就是你通过 Postman 得到结果的原因。

另一件事是,您已尝试将 Access-Control-Allow-Origin header 添加到请求中。这不是 CORS 规范所期望的。您需要在响应中包含 Access-Control-Allow-Origin header。这意味着它需要由 server-side.

添加

由于您正在调用第 3 方 API,我相信您无法控制服务器。因此要求通过设置 Access-Control-Allow-Origin 来处理 CORS 问题是不可能的。

假设您无权访问服务器,有 3 种方法可以解决此问题。

  1. 通过在浏览器中禁用 CORS 检查(不推荐用于生产)。

  2. 通过在浏览器中使用 CORS 插件(不推荐用于生产)。

  3. 通过代理请求资源 - 最简单的方法,你可以做的是,编写一个小型节点服务器(或者如果你已经有一个 back-end 将它与你的 front-end 你可以使用它)它为第 3 方 API 请求并发回响应。在该服务器响应中,您现在可以允许 cross-origin header。

根据此 3rd way I have made a small node server with express and called BANZAICLOUD 使用以下代码。

const express=require('express');
const request = require('request');
const app=express();

app.get('/data',(req,res,next)=>{
    request('https://banzaicloud.com/cloudinfo/api/v1/providers/google/services/compute/regions/asia-east2/products',
     function (error, response, body) {
         res.send(body)
    });  
});
const port =process.env.port || 3000;
app.listen(port,()=>{
    console.log(`From port ${port}`);
});

然后就可以在前端使用http://localhost:3000/data获取数据了

检查你的 headers。您可能正在发送外部 API 不喜欢的 headers(如 Authorization 等),这可能会导致此错误。