带有 PHP 标头的跨域请求标头 (CORS)

带有 PHP 标头的跨域请求标头 (CORS)

问题描述:

我有一个简单的 PHP 脚本,我正在尝试跨域 CORS 请求:

I have a simple PHP script that I am attempting a cross-domain CORS request:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
...

但我仍然收到错误:

请求头字段 X-Requested-With 不允许 Access-Control-Allow-Headers

Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers

有什么我遗漏的吗?

Access-Control-Allow-Headers 不允许 * 作为接受值,请参阅 Mozilla 文档此处.

Access-Control-Allow-Headers does not allow * as accepted value, see the Mozilla Documentation here.

您应该发送接受的标头,而不是星号(第一个 X-Requested-With 正如错误所说的那样).

Instead of the asterisk, you should send the accepted headers (first X-Requested-With as the error says).

* 现在被接受的是 Access-Control-Allow-Headers.

根据 MDN Web Docs 2021:

* 仅算作没有凭据的请求(没有 HTTP cookie 或 HTTP 身份验证信息的请求)的特殊通配符值.在带有凭据的请求中,它被视为没有特殊语义的文字头名称 *.请注意,Authorization 标头不能使用通配符,并且始终需要明确列出.

The value * only counts as a special wildcard value for requests without credentials (requests without HTTP cookies or HTTP authentication information). In requests with credentials, it is treated as the literal header name * without special semantics. Note that the Authorization header can't be wildcarded and always needs to be listed explicitly.