使用Mailgun的validate API时如何解决“无访问权限允许来源”问题?

时间:2019-09-03 02:58:42

标签: javascript mailgun

我要在通过unbounce创建的登录页面中添加自定义电子邮件字段验证功能,并决定使用Mailgun的validate API来执行此操作。但是,我收到了CORS错误。

我尝试过

request.setRequestHeader("Authorization", "Basic " + window.btoa("api:"KEY"));
request.setRequestHeader("Access-Control-Allow-Headers", "GET");

我的完整代码

function useMailGun() {
    let request = new XMLHttpRequest();
    request.open("GET", "https://api.mailgun.net/v4/address/validate", true);
    request.setRequestHeader("Authorization", "Basic " + window.btoa("api:KEY"));
    request.setRequestHeader("Access-Control-Allow-Headers", "GET");
    request.withCredentials = true;
    request.onload = function() {
      if (request.status >= 200 && request.status < 400) {
        let data = JSON.parse(request.response);
        if(data.reason.length > 0) {
          return false;
        }
        else {
          return true;
        }
      }
      else {
        console.error("Failed to load Mailgun's api");
        return false;
      }
    }
    request.onerror = function() {
      console.error("Failed to load Mailgun's api");
      return false
    }
    request.send({
      "address":$("#email").val(),
    });
  }

我收到的错误消息:

Access to XMLHttpRequest at 'https://api.mailgun.net/v4/address/validate' from origin 'website' 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.

1 个答案:

答案 0 :(得分:0)

在不使用代理的情况下使用前端javascript时,无法向Mailgun api发送请求。参见documentation

  

如果在浏览器中使用,则需要与之通信的代理   由于cors限制,请使用Mailgun API。另外,请勿发布您的   前端代码中的私人api密钥。

您必须使用代理或自行设置诸如node-js或php之类的后端服务来进行请求。