您好我正在尝试在JavaScript网络应用中向SparkPost API发送POST调用。它适用于curl和Postman,但是当我尝试从我的localhost网站发送时,我收到401 Unauthorized
错误。
我目前的代码如下所示,但我也尝试了fetch
,结果相同。
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));
}
我的凭据设置有问题吗?请注意,creds
设置为我的秘密API密钥字符串。
答案 0 :(得分:2)
在与Sparkpost开发者聊天后想出来 - 该服务只允许"严格的CORS"即来自服务器端的请求,我从客户端代码发送请求。