Home > front end >  I can't fetch data from the api using useEffect
I can't fetch data from the api using useEffect

Time:10-02

i'm just trying to implement a freecodecamp tutorial, in which we are creating a simple react-node app, here I'm unable to get the data from the api and I'm getting this error in my browser console

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

This is my server.js file

const express = require("express");

const PORT = process.env.PORT || 3001;

const app = express();

app.get("/api", (req, res) => {
  res.json({ message: "Hello from server!" });
});

app.listen(PORT, () => {
  console.log(`Server listening on ${PORT}`);
});

And this is the file where I'm fetching the data

import React from "react";
import logo from "./logo.svg";
import "./App.css";

function App() {
  const [data, setData] = React.useState(null);

  React.useEffect(() => {
    fetch("/api")
      .then((res) => res.json())
      .then((data) => setData(data.message));
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>{!data ? "Loading..." : data}</p>
      </header>
    </div>
  );
}

export default App;

CodePudding user response:

I think you have forgotten to use the full domain:

React.useEffect(() => {
    fetch("http://localhost:YOUR_PORT_NUMBER/api")
      .then((res) => res.json())
      .then((data) => setData(data.message));
  }, []);
  • Related