gpt4 book ai didi

javascript - 使用Mailgun的验证API时如何修复 "No Access-Control-Allow-Origin"?

转载 作者:行者123 更新时间:2023-11-28 03:35:40 24 4
gpt4 key购买 nike

我正在向通过 unbounce 创建的登陆页面添加自定义电子邮件字段验证功能,并决定使用 Mailgun 的验证 api 来执行此操作。但是,我收到 CORS 错误。

我已经尝试过

request.setRequestHeader("Authorization", "Basic " + window.btoa("api:"KEY"));
request.setRequestHeader("Access-Control-Allow-Headers", "GET");

我的完整代码

function useMailGun() {
let request = new XMLHttpRequest();
request.open("GET", "https://api.mailgun.net/v4/address/validate", true);
request.setRequestHeader("Authorization", "Basic " + window.btoa("api:KEY"));
request.setRequestHeader("Access-Control-Allow-Headers", "GET");
request.withCredentials = true;
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
let data = JSON.parse(request.response);
if(data.reason.length > 0) {
return false;
}
else {
return true;
}
}
else {
console.error("Failed to load Mailgun's api");
return false;
}
}
request.onerror = function() {
console.error("Failed to load Mailgun's api");
return false
}
request.send({
"address":$("#email").val(),
});
}

我收到的错误消息:

Access to XMLHttpRequest at 'https://api.mailgun.net/v4/address/validate' from origin 'website' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

最佳答案

在不使用代理的情况下使用前端 javascript 时,不可能向 Mailgun api 发出请求。请参阅documentation :

If used in the browser, a proxy is required to communicate with the Mailgun api due to cors limitations. Also, do not publish your private api key in frontend code.

您必须使用代理或自行设置后端服务(例如 Node-js 或 php)来发出请求。

关于javascript - 使用Mailgun的验证API时如何修复 "No Access-Control-Allow-Origin"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764526/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com