reactjsaxiosfetch-apidirectus

Unable to consume Directus API endpoint from React using Axios


I created an API endpoint using Directus to store some data. https://comfy-store.directus.app/items/products

I verified this endpoint was working using POSTMAN.

I then created a React app using Vite to try consume this endpoint using Axios.

I installed axios on my vite app but when I console.log my result I only get back 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>

Also, tried using fetch and getting same result

Can anyone tell me what I'm doing wrong?

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

Solution

  • You need to add the protocol to make a valid request to the end point like 'http://' or 'https://' to your URL

    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;
    

    I would suggest you to go through this documentation https://blog.logrocket.com/understanding-axios-get-requests/ for a better understanding on how to use axios get method. Happy Coding :)