Jake Rowsell
Jake Rowsell

Reputation: 466

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

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.com'      that is not equal to the supplied origin. Origin 'http://localhost' is   therefore not allowed access.

Upvotes: 0

Views: 8053

Answers (2)

Najim M
Najim M

Reputation: 23

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.com/itisnajim/sendgrid-nodejs

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

Ajax example:

let urlStr = "http://sendgrid-nodejs-oxailstudiosnode.7e14.starter-us-west-2.openshiftapps.com";
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))

    }
})

Upvotes: 2

bvanvugt
bvanvugt

Reputation: 1242

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.

Upvotes: 1

Related Questions