gpt4 book ai didi

javascript - AJAX错误: "Response to preflight request doesn' t pass access control check"

转载 作者:行者123 更新时间:2023-12-03 01:22:34 25 4
gpt4 key购买 nike

我在向 SendGrid 电子邮件 API 发出 POST 请求时遇到问题。

当我提交表单以发出 POST 请求时,我在控制台中收到以下错误:

Failed to load https://api.sendgrid.com/v3/mail/send: Response to preflight 
request doesn't pass access control check: The 'Access-Control-Allow-Origin'
header has a value 'https://sendgrid.api-docs.io' that is not equal to the
supplied origin. Origin 'https://example.com/' is therefore not
allowed access.

这是我的要求:

    $.ajax({
method: "POST",
url: 'https://api.sendgrid.com/v3/mail/send',
headers: {
'Authorization':'bearer XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
'Content-Type':'application/json'
},
data: {
"personalizations": [
{
"to": [
{
"email": "example@email.com"
}
],
"subject": 'Contact form submission - example.com'
}
],
"from": {
"email": sender
},
"content": [
{
"type": "text/plain",
"value": content
}
]
}
});

当我将以下行添加到数据中时:

dataType: 'jsonp',

错误消息更改为以下内容:

GET https://api.sendgrid.com/alongurl 405 (Method Not Allowed)

我不确定为什么当我将控制台设置为 POST 时控制台会发出 get 请求。我根本不知道为什么会发生这种情况。希望有人能指出我正确的方向。谢谢。

最佳答案

由于 CORS,您无法通过浏览器向发送网格 API 发送请求。可能有很多原因,但SendGrid doc explains exactly why并建议您创建一个 Web 服务器来发送请求

原因之一来自上面的链接

When you have a browser-only application that reaches out to APIs, the API key has to be embedded in the application. Anyone with access to a browser-only application can access all of the Javascript source code, including your API keys.

以及从链接执行此操作的建议方法

You can create a server based application, which will protect your API keys from being released to the world. Languages like NodeJS, PHP, Ruby, Python, C#, Go, and Java, and others can be implemented to make calls to the API from the security of a locked down server environment.

关于javascript - AJAX错误: "Response to preflight request doesn' t pass access control check",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51698581/

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