是否可以将请求标头添加到CORS预检请求中? [英] Is it possible to add a request header to a CORS preflight request?

查看:72
本文介绍了是否可以将请求标头添加到CORS预检请求中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网站可以从外部服务器(而不是服务器)访问API通过简单的 XmlHttpRequest (请参见下文)为网站提供服务.该API需要将用于访问服务的API密钥添加为请求标头.但是,由于它们是 CORS 请求浏览器首先执行预检请求,以检查该服务器是否支持CORS.现在,服务器似乎也想在其中查看API密钥这些由浏览器完成的预检请求.是否可以通过还是预检请求的API密钥?

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();

推荐答案

CORS预检 OPTIONS 请求完全由浏览器控制-因此无法向其添加任何请求标头.参见 https://fetch.spec.whatwg.org/#cors-preflight-fetch .因此,您向其发送请求的任何端点都必须配置为允许未经身份验证的 OPTIONS 请求,并以 200 OK 响应它们-至少在您的请求触发一个预检(如果您添加任何自定义请求标头,例如问题中的 x-api-key 标头,它将始终如此).

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).

这篇关于是否可以将请求标头添加到CORS预检请求中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆