Mailgun API: Request header field Authorization is not allowed by Access-Control-Allow-Headers

假如想象 提交于 2019-11-28 13:52:25

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:

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.

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

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!