0

i am trying to connect react frontend with express backend. I have added the URL of the API in .env file and also in a constant.js file. When i use base url from constant.js, data is being fetched but when i use the base url from .env file i am getting the below error

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

Can anyone explain why this is happening?

App.jsx code:

import { useEffect, useState } from 'react';
import './App.css';
import { List } from './components/List';
// import {baseUrl} from "./utils/constants"

function App() {
  const [input, setInput] = useState("")
  const [tasks, setTasks] = useState([])

  const getTasks =  async () => {
    try{
      const res = await fetch(`${process.env.REACT_APP_BASE_URL}/get`)
      const data = await res.json();
      console.log(data)
      setTasks(data.data)
    }
    catch(error){
      console.log(error)
    }
  }

  useEffect(() => {
    getTasks();
    console.log(tasks)
  },[])

  return (
    <div className="App">
      <h1>CRUD Operations </h1>

      <div className="input_holder">
        <input type="text" value={input} onChange={(e) => setInput(e.target.value)}/>
        <button type='submit'>Add Task</button>
      </div>

      <ul>
        {tasks.map( (task) => {
         return <List key={task._id} id={task._id} task={task.task} />
        })}
      </ul>
    </div>
  );
}

export default App;

.env file:

REACT_APP_BASE_URL = "http://localhost:4000/api/v1"

express code:

exports.getTask = async (req, res) => {
  try {
    const tasks = await Task.find();
    res.status(200).json({
      success: true,
      message: "All tasks fetched",
      data: tasks,
    });
  } catch (error) {
    console.log(error);
    res.status(500).json({
      success: false,
      message: "Internal server error",
    });
  }
};

0 Answers0