1

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

1 Answer 1

1

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.