无法使用 Axios 从 React 使用 Directus API 端点

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

我使用 Directus 创建了一个 API 端点来存储一些数据。 https://comfy-store.directus.app/items/products

我使用 POSTMAN 验证了此端点是否正常工作。

然后我使用 Vite 创建了一个 React 应用程序,尝试使用 Axios 使用此端点。

我在我的 vite 应用程序上安装了 axios,但是当我 console.log 我的结果时,我只得到 HTML

<!doctype html>
<html lang="en">
  <head>
    <script type="module">
import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>

    <script type="module" src="/@vite/client"></script>

    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx?t=1726068244011"></script>
  </body>
</html>

另外,尝试使用 fetch 并得到相同的结果

谁能告诉我我做错了什么?

import axios from 'axios';

function App() {
  const apiTest = async () => {
    try {
      const result = await axios.get('comfy-store.directus.app/items/products').then((res) => {
        console.log(res.data)
      })
    } catch (e) {
      console.log(e)
    }
  }

  apiTest()

  return (
    <div>
      Test
    </div>
  )
}

export default App
reactjs axios fetch-api directus
1个回答
0
投票

您需要在调用“http://”或“https://”时将协议添加到端点

import axios from 'axios';
import { useEffect } from 'react';

function App() {
const apiTest = async () => {
try {
  const result = await 
  axios.get('https://comfystore.directus.app/items/products');
  console.log(result.data);  // Now this will log the response data
  } catch (e) {
  console.log(e);  // Catch any errors and log them
 }
};

// Using useEffect to prevent the API call from being triggered on every 
render
useEffect(() => {
    apiTest();
}, []);

return (
  <div>
    Test
  </div>
 );
}

export default App;

我建议您阅读此文档https://blog.logrocket.com/understanding-axios-get-requests/ 为了更好地理解如何使用 axios get 方法。 快乐编码:)

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.