-1

React JS: DB API connection error

I want to connect to DB API, but I can't resolve the below error.

- courseApi.js:10 GET http‍://localhost:3001/courses/ net::ERR_CONNECTION_REFUSED
- react_devtools_backend_compact.js:2367 API call failed. TypeError:
Failed to fetch
- Uncaught (in promise) TypeError: Failed to fetch
at getCourses (courseApi.js:10:1)
at CoursesPage.js:9:1

App.js

import React from "react";
import HomePage from "./HomePage";
import CoursesPage from "./CoursesPage";
// import CourseForm from "./CourseForm";
import AboutPage from "./AboutPage";
import Header from "./common/Header";
import { Route, Switch, Redirect } from "react-router-dom";
import { ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import NotFoundPage from "./NotFoundPage";
import ManageCoursePage from "./ManageCoursePage";

function App() {
  return (
    <div className="container-fluid">
      <ToastContainer
        autoClose={3000} 
        hideProgressBar
      />
      <Header />
      <Switch>
        <Route path="/" exact component={HomePage} />
        <Route path="/courses" component={CoursesPage} />
        <Route path="/course" component={ManageCoursePage} />
        <Route path="/course/:slug" component={ManageCoursePage} />
        <Route path="/about" component={AboutPage} />
        <Route component={NotFoundPage} />
        <Redirect from="/about-page" to="/about" />
      </Switch>
    </div>
  );
}

export default App;

index.js

import "bootstrap/dist/css/bootstrap.min.css";
import React from "react";
// import ReactDOM from "react-dom";
import { BrowserRouter as Router } from "react-router-dom";

import App from "./components/App";
import * as ReactDOM from "react-dom/client";
const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  <Router>
    <App />
  </Router>
);

CoursePage.js

import React, { useState, useEffect } from "react";
import { getCourses } from "../api/courseApi";
import CourseList from "./CourseList";

function CoursesPage() {
  const [courses, setCourses] = useState([]);

  useEffect(() => {
    getCourses().then((_courses) => setCourses(_courses));
  }); 

  return (
    <>
      <div className="container-fluid">
        <h1>Course Page</h1>
        <a className="btn btn-primary" href="/course">
          Add course
        </a>
        <CourseList courses={courses} />
      </div>
    </>
  );
}

export default CoursesPage;

courseApi.js

import { handleResponse, handleError } from "./apiUtils";
const baseUrl = process.env.REACT_APP_API_URL + "/courses/";

export function getCourses() {
  console.log(baseUrl);
  // console.log(handleResponse);
  // console.log(handleError);
  // debugger;
  console.log(window.location.href);
  return fetch(baseUrl).then(handleResponse).catch(handl`your text`eError);
}

export function getCourseBySlug(slug) {
  return fetch(baseUrl + "?slug=" + slug)
    .then((response) => {
      if (!response.ok) throw new Error("Network response was not ok.");
      return response.json().then((courses) => {
        if (courses.length !== 1) throw new Error("Course not found: " + slug);
        return courses[0]; // should only find one course for a given slug, so return it.
      });
    })
    .catch(handleError);
}

export function saveCourse(course) {
  return fetch(baseUrl + (course.id || ""), {
    method: course.id ? "PUT" : "POST", // POST for create, PUT to update when id already exists.
    headers: { "content-type": "application/json" },
    body: JSON.stringify({
      ...course,
      // Parse authorId to a number (in case it was sent as a string).
      authorId: parseInt(course.authorId, 10),
    }),
  })
    .then(handleResponse)
    .catch(handleError);
}

export function deleteCourse(courseId) {
  return fetch(baseUrl + courseId, { method: "DELETE" })
    .then(handleResponse)
    .catch(handleError);
}

apiUtils.js

export async function handleResponse(response) {
  if (response.ok) return response.json();
  if (response.status === 400) {
    // So, a server-side validation error occurred.
    // Server side validation returns a string error message, so parse as text instead of json.
    const error = await response.text();
    throw new Error(error);
  }
  throw new Error("Network response was not ok.");
}

// In a real app, would likely call an error logging service.
export function handleError(error) {
  // eslint-disable-next-line no-console
  console.error("API call failed. " + error);
  throw error;
}

package.json

...
"scripts": {
   "start": "run-p start:dev start:api",
   "start:dev": "cross-env REACT_APP_API_URL=http://localhost:3001 react-scripts start",
   "prestart:api": "node tools/createMockDb.js",
  ...
 }
}
...
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
J. Nam
  • 1
  • 1
  • 1
    Is the backend/db server running? This appears to be more an issue with where & how the backend is running and handling requests. Can you [edit] to provide those details and [mcve]? – Drew Reese May 22 '23 at 16:51
  • @DrewReese I checked it was not running. when I made it run manually, I didnt get this error. Could you please advise me how to fix the server issue? And thank you for advising. – J. Nam May 25 '23 at 22:25
  • So when the server is running you don't have any errors or issues? What other server issue do you need advisement on? – Drew Reese May 25 '23 at 22:30

1 Answers1

0

you should add [] to call the function only once on mount of component and to avoid the infinite call in

useEffect(() => {
    getCourses().then((_courses) => setCourses(_courses));
  }, []); 

and i think you should verify if you are passing the correct URL const baseUrl = process.env.REACT_APP_API_URL + "/courses/";

  • Good catch, but this would cause a render looping issue in the frontend, not a backend DB access error. OP has several frontend UI issues unrelated to the DB access. This won't answer/address the issue OP is asking about. – Drew Reese May 22 '23 at 16:48
  • Hi, I fixed it but still error is appearing – J. Nam May 25 '23 at 22:26