WordPress和VueJS:预检响应中的访问控制允许标头

uqxowvwt  于 2022-11-22  发布在  WordPress
关注(0)|答案(1)|浏览(530)

我尝试获取从candriam-app.nanosite.tech到candriam.nanosite.tech的路由,我尝试了几种方法来允许标头,但仍然出现此错误

Access to fetch at 'https://xxxA/wp-json/nf-submissions/v1/form/1' from origin 'https://xxxB' has been blocked by CORS policy: Request header field nf-rest-key is not allowed by Access-Control-Allow-Headers in preflight response.

我想创建一个网站xxxA的无头WordPress。我可以从www.example.com在WP Rest API上执行请求,没有任何问题candriam-app.nanosite.tech,但我有这个扩展创建的端点的问题:https://github.com/haet/ninja-forms-submissions-rest-endpoint
我按照文档和我的代码来执行请求,如下所示:

export async function getApiContactForm(route, params = { method: 'get' }) {
  const data = await fetch(route, {
    method: params.method,
    headers: {
      'Content-Type': 'application/json',
      'NF-REST-Key': 'xxxxxxxxxxx',
    },
  })
  const body = data.json()
  return body
}

NF-Rest-Key当然与模块给出的相同。
我在服务器端尝试了不同的方法:
在functions.php中,我尝试了以下代码:

header( 'Access-Control-Allow-Origin: * ' );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );
header( 'Access-Control-Allow-Headers: nf-rest-key' );

在xxxxxA的.htaccess文件中,我尝试了以下代码:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

我阿索试探着:

Header set Access-Control-Allow-Origin *
Header set AMP-Access-Control-Allow-Source-Origin *

但我还是得到了错误。
是否有可能插件是bug?我必须特别允许这个插件,这个头(nf-rest-key)从服务器?
当我检查服务器的标头时(如这里:https://securityheaders.com/)我是否应该看到存储我的应用程序的网站已获得授权?

toiithl6

toiithl61#

我通过将以下代码添加到functions.php来解决这个问题:

add_action('init', 'handle_preflight');
function handle_preflight()
{

    $origin = get_http_origin();
    if ($origin == 'http://localhost:8080' ||    $origin == 'https://xxxxxB') {
        // You can set more specific domains if you need
        header("Access-Control-Allow-Origin: " . $origin);
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
        header("Access-Control-Allow-Credentials: true");
        header('Access-Control-Allow-Headers: NF-REST-Key, Content-Type');

        if ('OPTIONS' == $_SERVER['REQUEST_METHOD']) {
            status_header(200);
            exit();
        }
    }
}

相关问题