如何使用Auth1.0将woocommerce与React连接?

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

我正在尝试将我的电子商务平台集成到我的 React 应用程序中。但我无法连接。我总是遇到错误。 这时候CORS错误就来了。我不明白如何解决这个问题。

请检查我的代码并告诉我是否有人可以帮助我。 这是可用的工作代码。

此 API 在 Postman 中运行良好。

https://9000-monospace-my-test-app-1715420758185.cluster-3g4scxt2njdd6uovkqyfcabgo6.cloudworkstations.dev/?monospaceUid=683162

import { useEffect, useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
import OAuth from 'oauth-1.0a';
import axios from 'axios';
import CryptoJS from 'crypto-js';


function App() {
  const [count, setCount] = useState(0)

  const customer_key = '*******************************';
  const consumer_key = '*******************************';


  const [posts, setPosts] = useState([]);
  
  useEffect(() => {
    const oauth = OAuth({
      consumer: {
        key: customer_key,
        secret: consumer_key
      },
      signature_method: 'HMAC-SHA1',
      hash_function(base_string, key) {
        return CryptoJS.enc.Base64.stringify(CryptoJS.HmacSHA1(base_string, key));
      }
    });

    const request_data = {
      url: 'http://localhost/wordpress/wp-json/wc/v3/products',
      method: 'GET'
    };

    const authorization = oauth.authorize(request_data);

    const headers = oauth.toHeader(authorization);
    
    axios.get(request_data.url, { headers })
      .then(response => {
        setPosts(response.data);
      })
      .catch(error => {
        console.error('Error fetching posts:', error);
      });
  }, []);



  return (
    <>
     <div>
      <h1>Sample OAuth 1.0a Authenticated API Data</h1>
      <ul>
        {posts.map(post => (
          <li key={post.id}>
            <h2>{post.title}</h2>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
    </div>
    </>
  )
}

export default App

任何解决方案表示赞赏!

reactjs wordpress woocommerce woocommerce-rest-api
1个回答
0
投票

要使用 OAuth 1.0 将 WooCommerce 与 React 连接,您需要处理 CORS(跨源资源共享)错误。当您的 React 应用程序尝试向托管在不同域上的 WooCommerce API 发出请求时,会发生这些错误。

要解决 CORS 错误,您可以将服务器配置为允许跨源请求或使用代理服务器。此外,请确保您已在 React 应用程序中正确设置 OAuth 1.0 身份验证,以验证对 WooCommerce API 的请求。

如果您仍然遇到问题,您可能需要检查代码并调试任何潜在的错误或错误配置。如果您需要进一步的帮助,请考虑联系WPCommerz,这是一家专门从事 WordPress 插件的软件公司。他们可能会提供指导或解决方案,以帮助将 WooCommerce 无缝集成到您的 React 应用程序中。

© www.soinside.com 2019 - 2024. All rights reserved.