【问题标题】:woocommerce rest api: can't get preflight request to passwoocommerce rest api:无法通过预检请求
【发布时间】:2019-11-26 21:46:09
【问题描述】:

我有一个 woocommerce 网站,我希望它的 REST API 向全世界开放。

我了解到需要设置 CORS 标头,所以我 google 并设置了以下钩子:

add_action('rest_api_init', function() {
remove_filter('rest_pre_serve_request', 'rest_send_cors_headers');   
add_filter('rest_pre_serve_request', function( $value ) {
    header( 'Access-Control-Allow-Origin: *' );
    header( 'Access-Control-Allow-Methods: OPTIONS, GET, POST, PUT, PATCH, DELETE' );
    header( 'Access-Control-Allow-Credentials: true' );
    header('Access-Control-Allow-Headers: Authorization,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Origin,Content-Type,X-Auth-Token,Content-Range,Range');
    return $value;
});
}, 15);

我确认我的服务器正在响应正确的 CORS 标头:

访问控制允许凭据:true

访问控制允许标头:

授权,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Origin,Content-Type,X-Auth-Token,Content-Range ,范围

访问控制允许方法:OPTIONS、GET、POST、PUT、PATCH、DELETE

访问控制允许来源:*

Access-Control-Expose-Headers:X-WP-Total、X-WP-TotalPages

然后我开始编写客户端代码:

xhr = new XMLHttpRequest();
xhr.open('POST', 'https://..../wp-json/wc/v3/products');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('mykey:mysecret'));
xhr.send(JSON.stirngify({ ... });

以上代码是在 Chrome 控制台的 https://google.com 标签下输入的。我只是无法让预检请求工作,这是错误:

选项https://..../wp-json/wc/v3/products401(未经授权)

从源访问“https://..../wp-json/wc/v3/products”处的 XMLHttpRequest “https://www.google.com”已被 CORS 策略阻止:响应 预检请求未通过访问控制检查:它没有 HTTP 正常状态。

即使响应标头与上面发布的完全一样。

我做错了什么?

【问题讨论】:

  • stackoverflow.com/a/44884623/441757 上查看答案。您需要为 OPTIONS 请求添加处理,该答案解释了如何在 Apache 配置中添加该处理。我认为可能有必要在 Apache 配置中执行此操作,而不是在您的 woocommerce/wordpress/php 代码中

标签: wordpress rest woocommerce cors


【解决方案1】:

如果您使用的是:“Access-Control-Allow-Credentials”=true,请确保“Access-Control-Allow-Origin”不是“*”,必须使用正确的域进行设置!

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 2021-08-08
    • 2016-08-20
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 2014-03-21
    • 1970-01-01
    • 2017-07-04
    相关资源
    最近更新 更多