2

Hi I'm trying to send a POST call to the SparkPost API in a JavaScript web app. It works fine with curl and Postman, but as soon as I try sending from my localhost site I get a 401 Unauthorized error.

My current code looks like the below, but I've tried fetch as well with the same results.

sendEmail(subject, data) {
let textbody = "blah blah blah";
const url = "https://api.sparkpost.com/api/v1/transmissions";
const fetchbody = {
  content: {
    from: "sandbox@sparkpostbox.com",
    subject: subject,
    text: textbody
  },
  recipients: [{address: "myaddress@gmail.com"}]
};
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
    console.log(this.responseText);
  }
});
xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("accept", "application/json");
xhr.setRequestHeader("authorization", creds);
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(JSON.stringify(fetchbody));
}

Is there something wrong with my credentials setup here? Note that creds is set to my secret API key string.

Grokify
  • 15,092
  • 6
  • 60
  • 81
nrflaw
  • 840
  • 8
  • 13

1 Answers1

3

Figured it out after chatting with the Sparkpost devs a bit - the service only allows "strict CORS" i.e. requests from server-side, and I was sending the request from client-side code.

nrflaw
  • 840
  • 8
  • 13