如何修复被 cors 策略阻止的 Angular 第三方 API 调用?

问题描述

我创建了一个简单的应用程序,其中包含第三方电子邮件发送 API 实现,以通过联系表获取电子邮件。当我在本地主机或 github 页面上运行该应用程序时,出现此错误

Access to XMLHttpRequest at 'https://api.mailjet.com/v3.1/send' from origin 'https://myrepo.github.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

该问题的解决方案是什么。显然我不能在 API 端应用任何解决方案,我所要做的就是从我的角度代码。 这是我在 http post 请求中实现的内容

sendMail(): Observable<any>{
    let API_URL='https://api.mailjet.com/v3.1/send';
    let data={
      "Messages":[
        {
          "From": {
            "Email": "myemail@gmail.com","Name": "My Name"
          },"To": [
            {
              "Email": "myemail@gmail.com","Name": "My Name"
            }
          ],"Subject": "My first Mailjet email","TextPart": "Greetings from Mailjet.","HTMLPart": "<h3>Dear passenger 1,welcome to <a href=https://www.mailjet.com/>Mailjet</a>!</h3><br />May the delivery force be with you!","CustomID": "AppGettingStartedTest"
        }
      ]
    };
    console.log('sending email....')
    console.log(data);
    this.httpClient.post<any>(API_URL,data,{
      headers: new HttpHeaders({
        'Content-Type':'application/json','Authorization':'Basic VGIzOTIsasdasdasdasdasdrewetwfdsfasdasMjI0NWUVcDFGA='
      })
    }).subscribe(res=>{
      console.log(res);
    },err=>{
      console.log(err);
    });
    return null;//ignoring this for Now.

  }

解决方法

你不能。您必须使用像 PHP 这样的服务器端实现,因为据我所知,您无法使用 mailjet 通过客户端发送电子邮件。它也不安全,因为您必须在 Angular 应用程序中提及您的 API 密钥。想象一下,如果有人对您的 Angular 应用程序进行逆向工程,并读取您的 API 密钥?通过 Angular 服务文件中的以下 Typescript 函数向您的 PHP 文件发送请求。确保也指定其 URL。内容具有三个属性,电子邮件、主题和消息。您必须先为它们赋值,然后再将它们传递给 sendEmail 函数的参数。

客户端实现

T *a[N];       // a is an array of pointer to T
T (*a)[N];     // a is a pointer to an array of T
T *f();        // f is a function returning a pointer to T
T (*f)();      // f is a pointer to a function returning T

服务器端实现

  public sendEmail(content: object): Observable<any> {
    return this.httpClient.post(this.SMTPURL,JSON.stringify(content));
  }
,

我认为您应该将 Web 服务器配置为代理或使用配置 Angular CLI 代理进行开发。

,

根据 this question 的说法,最好有一个与您的 API 对话的服务器端功能。我不知道是不是你的情况,但它可以工作