Is it possible to add a request header to a CORS preflight request?

我的梦境 提交于 2020-12-12 10:34:05

问题


I have a website that accesses an API from an external server (not the server that serves the website) via a plain XmlHttpRequest (see below). That API requires an API key for accessing the service to be added as request header. However, as these are CORS requests the browser first does a preflight request to check if that server supports CORS. Now, it seems that the server also wants to see the API key in these preflight requests that are done by the browser. Is it possible to pass the API key also to the preflight request?

const req = new XMLHttpRequest();
req.open("GET", "https://some/api/endpoint");
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.setRequestHeader("x-api-key", _apiKey);
req.onload = () => {
  // ...
};
req.send();

回答1:


The CORS preflight OPTIONS request is completely controlled by the browser — so it’s not possible to add any request headers to it. See https://fetch.spec.whatwg.org/#cors-preflight-fetch. That’s why any endpoint you send a request to must be configured to allow unauthenticated OPTIONS requests, and respond to them with a 200 OK — at least as long as your request triggers a preflight (which it always will if you add any custom request headers, such as the x-api-key header in the question).



来源:https://stackoverflow.com/questions/58547499/is-it-possible-to-add-a-request-header-to-a-cors-preflight-request

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