首页 > 解决方案 > 离子角度中的 Woocommerce-api CORS 错误

问题描述

我被困在这个地方好几天了。我google了无数次,找不到答案。我只是在制作一个简单的离子应用程序,从我的 wordpress 网站获取产品。当我在终端中尝试“离子服务”时,出现以下错误。

Access to fetch at 'http://axx.nwh.mybluehost.me/WooIonic/wc-api/wc/v3/products?oauth_consumer_key=ck_1085532f8447ad05f7a77766ba54c62b131edcb6&oauth_nonce=bXnOUgfqbVJyVl4fPTwcwxV7cKVX9Ldx&oauth_signature_method=HMAC-SHA256&oauth_timestamp=1591298066&oauth_version=1.0&oauth_signature=39bmDp8bPyXeRRk7M62Wz%2Fjkbk35N%2F4XJ3jnarY1QlM%3D' from origin 'http://localhost:8100' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我已经安装了woocommerce-api,我的源代码如下:

import WooCommerceRestApi from 'woocommerce-api';
export class HomePage implements OnInit {
   WooCommerce: any;

   constructor() {
       this.WooCommerce = new WooCommerceRestApi({
           url: 'http://axx.nwh.mybluehost.me/WooIonic',
           consumerKey: 'ck_xxxxxxxxxxxxxxxxxxxxx',
           consumerSecret: 'cs_xxxxxxxxxxxxxxxxxxxxx',
           version: 'wc/v3'
       });
       this.WooCommerce.getAsync('products').then((data) => {
           console.log(data);
       }, (err) => {
       console.log(err);
       });
    }
    ngOnInit() { }
 }

我在谷歌上查找了一些关于禁用 chrome 上的网络安全或在主题的 functions.php 中添加钩子的答案,但事实证明它们都不适用于我的情况。下面是我在我的网站店面主题的functions.php中添加的代码。

function add_cors_http_header(){
    header("Access-Control-Allow-Origin: http://localhost:8100");
    header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS, READ');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, authorization, 
          XMLHttpRequest, user-agent, accept');
    header("Access-Control-Allow-Credentials: true");

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

add_filter('kses_allowed_protocols', function($protocols) {
    $protocols[] = 'ionic';
    return $protocols;
});

有人可以帮我解决这个问题吗?我真的需要你的帮助,我将非常感谢任何形式的回答。以防万一,我有最新版本的 ionic、wordpress(bluehost) 和 woocommerce。我将期待您的回答。此致。龙马林

标签: angularwordpressionic-frameworkwoocommerce

解决方案


推荐阅读