仅在Chrome上,CORS的飞行前响应不成功

时间:2020-07-21 20:36:31

标签: wordpress api rest woocommerce

我是新手,我正在尝试通过WooCommerce api从Wordpress发出请求API调用: https://docs.woocommerce.com/document/woocommerce-rest-api/

我正在使用Vuejs 2的前端和WooCommerce API从Wordpress获得产品,但是我得到了:

在Chrome / Edge上,我收到产品json,但出现以下错误:“拒绝设置不安全的标头“ User-Agent” Chrome error image

我尝试编辑wordpress的.htaccess,还编写了一个函数来正确设置标头,但一无所获。

我当然是错误的方法,我想知道如何解决这个问题。显然,我与axios遇到了同样的错误。我认为问题出在后端。我刚接触CORS。

WordPress:

header("Access-Control-Allow-Origin: http://localhost:8080"); // Also with *
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Headers: Authorization, content-type');

JS

  import WooCommerceAPI from "@woocommerce/woocommerce-rest-api";

WooCommerce.get("products", {
    per_page: 20, // 20 products per page

  })
    .then((response) => {
      // Successful request
      console.log("Response Status:", response.status);
      console.log("Response Headers:", response.headers);
      console.log("Response Data:", response.data);
      console.log("Total of pages:", response.headers['x-wp-totalpages']);
      console.log("Total of items:", response.headers['x-wp-total']);
    })
    .catch((error) => {
      // Invalid request, for 4xx and 5xx statuses
      console.log("Response Status:", error.response.status);
      console.log("Response Headers:", error.response.headers);
      console.log("Response Data:", error.response.data);
    })
    .finally(() => {
      // Always executed.
    });

非常感谢!

0 个答案:

没有答案
相关问题