更新时间:2022-05-20 22:37:38
您无法进行身份验证从浏览器中运行的前端JavaScript代码请求Mailgun API。 Mailgun API故意不支持根据他们自己的文档:
You can’t make authenticated requests to the Mailgun API from frontend JavaScript code running in a browser. The Mailgun API intentionally doesn’t support that, per their own documentation:
注意:如果在浏览器中使用,由于cors限制,需要代理与Mailgun api通信。另外,不要在前端代码中发布私有api密钥。
NOTE: 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.
具体来说,对于在浏览器中运行的前端JavaScript代码的请求,Mailgun API不允许授权
请求标头。你可以用 curl
或类似的方式验证:
Specifically, for requests from frontend JavaScript code running in browsers, the Mailgun API doesn’t allow the Authorization
request header. You can verify that with curl
or such:
$ curl -X OPTIONS -H "Origin: https://marquesslondon.com" \
-i https://api.mailgun.net/v3/marquesslondon.com/messages
HTTP/1.1 200 OK
Access-Control-Allow-Headers: Content-Type, x-requested-with
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Access-Control-Max-Age: 600
Allow: POST, OPTIONS
注意端点返回的 Access-Control-Allow-Headers
响应头的值不包括授权
。这意味着浏览器会阻止您的前端JavaScript代码发送包含授权
请求标头的任何请求的API端点。
Notice the value of the Access-Control-Allow-Headers
response header that endpoint returns doesn’t include Authorization
. That means browsers will block your frontend JavaScript code from sending that API endpoint any request that includes the Authorization
request header.
对于 http://marquesslondon.com
网站的 .htaccess
文件的更改,这些是不必要的和不相关的;你从那个(你的)网站返回的CORS标题并不重要,因为它只是发起请求的网站 - 你没有发送任何请求到它的跨域。
As far as your changes to the .htaccess
file for the http://marquesslondon.com
site, those are unnecessary and irrelevant; it it doesn’t matter what CORS headers you return from that (your) site, because it’s just the site initiating the request — you’re not sending any requests to it cross-origin.
相反重要的是您实际向跨域发送请求的网站返回的CORS标头,即 https://api.mailgun。净
。如上所述,该站点返回一个CORS Access-Control-Allow-Headers
响应标头,告诉浏览器不允许包含授权的请求
header - 这就是导致您在问题中看到请求标题字段不允许授权错误消息的原因。
Instead what matters are the CORS headers returned by the site you are actually sending a request to cross-origin, which is https://api.mailgun.net
. And as explained above, that site returns a CORS Access-Control-Allow-Headers
response header which tells browsers not to allow requests that include the Authorization
header — and that’s what results in you seeing the Request header field Authorization is not allowed error message cited in the question.