最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - CORS: Access-Control-Allow-Origin not equal to supplied origin - Stack Overflow

programmeradmin1浏览0评论

I'm trying to send an email from an application using sendgrid. This shouldn't be too difficult, and with PHP I've sent emails before. In this case I want to do it in Javascript as it's part of an Ember application. The first problem is the "No 'Access-Control-Allow-Origin" message, which I tried to solve with CORS. Now I've just got a different error!

Now I'm not sure where to look for tackling this issue. The code I'm using is the following:

(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(); 
}

This gives me the error:

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

I'm trying to send an email from an application using sendgrid. This shouldn't be too difficult, and with PHP I've sent emails before. In this case I want to do it in Javascript as it's part of an Ember application. The first problem is the "No 'Access-Control-Allow-Origin" message, which I tried to solve with CORS. Now I've just got a different error!

Now I'm not sure where to look for tackling this issue. The code I'm using is the following:

(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(); 
}

This gives me the error:

The 'Access-Control-Allow-Origin' header has a value 'https://sendgrid.'      that is not equal to the supplied origin. Origin 'http://localhost' is   therefore not allowed access.
Share Improve this question asked Apr 5, 2015 at 15:14 Jake RowsellJake Rowsell 4666 silver badges16 bronze badges 1
  • are you calling this code from https://sendgrid.? if not, nothing much you can do directly from javascript. server have to send to actual domain you gonna use or *. – YOU Commented Apr 5, 2015 at 15:17
Add a ment  | 

2 Answers 2

Reset to default 2

sendGrid CORS policy does not allow browsers to call their API (except if your are on "sendgrid.api-docs.io" domain) ... You have to send email from your server,

but if just for test or development purpose you can use my demo on github https://github./itisnajim/sendgrid-nodejs

post your data to http://sendgrid-nodejs-oxailstudiosnode.7e14.starter-us-west-2.openshiftapps.

Ajax example:

let urlStr = "http://sendgrid-nodejs-oxailstudiosnode.7e14.starter-us-west-2.openshiftapps.";
const msg = {
    "personalizations": [
        {"to": [{"email": "[email protected]"}]}
    ],
    "from": {"email": "[email protected]"},
    "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))

    }
})

It looks like you're calling the SendGrid API from an Ember app running in your browser? If so, you probably shouldn't be (for a number of security reasons).

You'll want to make an AJAX request to a server running on your own domain, and have your server

  • validate that the request is legitimate, and
  • call the SendGrid API to send the email

Exposing your SendGrid API key, and calling the API directly from a browser exposes your SendGrid account to potential abusers.

For the server-side API call, check out SendGrid's API Clients. You shouldn't need to write the API calls yourself.

发布评论

评论列表(0)

  1. 暂无评论