Wordpress 自定义 CORS 标头未获授权

问题描述 投票:0回答:1

嘿,当我尝试使用 Javascript fetch 访问某些数据时,出现此错误消息:

x-faustwp-secret headers is not authorized

let response = await fetch('https://mywebsite.com/?rest_route=/faustwp/v1/authorize', {
    headers: {
        'Content-Type': 'application/json',
        'x-faustwp-secret': apiClientSecret,
    },
    method: 'POST',
    body: JSON.stringify({
        code
    }),
});

当我使用扩展绕过 CORS 时(例如这个扩展 https://addons.mozilla.org/fr/firefox/addon/cors-everywhere/),一切都完美运行

所以我认为由于某种原因我的 CORS 标头在我的 Wordpress 中被忽略了

function.php
我添加了 :

function add_cors_http_header(){
    header("Access-Control-Allow-Headers: * , x-faustwp-secret"); // also tried without the *
    header("Access-Control-Allow-Origin: *");
}
add_action( 'send_headers', 'add_cors_http_header' );

我什至尝试使用以下方法直接在 .htaccess 文件中添加标头:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Headers "* , x-faustwp-secret"
</IfModule>

有人知道它可能来自哪里或遇到过这个问题吗?我联系了网络服务器的支持人员,但他们无法提供帮助。

php wordpress cors
1个回答
1
投票

感谢@ChrisHaas,我找到了使用

rest_allowed_cors_headers

的解决方案
function custom_rest_cors_headers( $headers ) {
    $headers[] = "*";
    return $headers;
}
add_filter( 'rest_allowed_cors_headers', 'custom_rest_cors_headers' );
© www.soinside.com 2019 - 2024. All rights reserved.