繁体   English   中英

CORS:访问控制允许来源不等于提供的来源

[英]CORS: Access-Control-Allow-Origin not equal to supplied origin

我正在尝试使用sendgrid从应用程序发送电子邮件。 这应该不太困难,并且在使用PHP之前,我已经发送过电子邮件。 在这种情况下,由于它是Ember应用程序的一部分,所以我想用Javascript来实现。 第一个问题是“ No'Access-Control-Allow-Origin”消息,我尝试使用CORS解决。 现在,我有一个不同的错误!

现在,我不确定在哪里寻找解决此问题的方法。 我正在使用的代码如下:

(function(){
  makeCorsRequest('GET', mailUrl); 
})();

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    xhr = null;
  }
  return xhr;
}

function makeCorsRequest(type, url) {
  var xhr = createCORSRequest(type, url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }
  xhr.onload = function() {
    var text = xhr.responseText;
    console.log(text);
    var title = getTitle(text);
    alert('Response from CORS request to ' + url + ': ' + title);
  };

  xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
  };

  xhr.send(); 
}

这给了我错误:

The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.com'      that is not equal to the supplied origin. Origin 'http://localhost' is   therefore not allowed access.

看来您是从浏览器中运行的Ember应用程序调用SendGrid API的? 如果是这样,出于多种安全原因,您可能不应该这样做。

您需要向在您自己的域上运行的服务器发出AJAX请求,并让您的服务器

  • 验证请求是否合法,并且
  • 调用SendGrid API发送电子邮件

公开您的SendGrid API密钥,然后直接从浏览器调用API,会使您的SendGrid帐户暴露给潜在的滥用者。

对于服务器端API调用,请检出SendGrid的API客户端 您不需要自己编写API调用。

sendGrid CORS策略不允许浏览器调用其API(除非您位于“ sendgrid.api-docs.io”域上)...您必须从服务器发送电子邮件,

但是如果只是出于测试或开发目的,您可以在github https://github.com/itisnajim/sendgrid-nodejs上使用我的演示

将您的数据发布到http://sendgrid-nodejs-oxailstudiosnode.7e14.starter-us-west-2.openshiftapps.com

Ajax示例:

let urlStr = "http://sendgrid-nodejs-oxailstudiosnode.7e14.starter-us-west-2.openshiftapps.com";
const msg = {
    "personalizations": [
        {"to": [{"email": "example1@mail.com"}]}
    ],
    "from": {"email": "example2@mail.com"},
    "subject": "subject example",
    "content": [{"type": "text/plain", "value": "example body text"}]
};

$.ajax({
    url: urlStr,
    type: 'post',
    data: JSON.stringify(msg),
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Authorization", "Bearer API_KEY_HERE")
    },
    success: function(data){
        //console.log(data);
        //OK: Mail sent!!
    },
    error: function( jqXhr, textStatus, errorThrown ){
        //console.log( errorThrown, textStatus, jqXhr );
        if(jqXhr.status === 202 || jqXhr.status === "202"){
            //OK: Mail sent!!
        }else
        console.error("Mail not sent! Err:"+JSON.stringify(errorThrown))

    }
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM