如何修复被 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": "[email protected]","Name": "My Name"
          },"To": [
            {
              "Email": "[email protected]","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.

  }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)