-2

Hey guys I recently finished learning React and Nodejs. The thing is I don't know how to connect the two to have a fullstack app. Can you guys help me with that please? What libraries are the best in which you've used.

  • what do you mean by connect ? you need to run the nodejs server on a local port, and then do your HTTP requests in the frontend with a library like axios or fetch – VersifiXion Feb 11 '22 at 22:52
  • Yes. Make a server with nodejs and connect it user side made with reactjs –  Feb 11 '22 at 23:08
  • no need for a library, just use the fetch api. https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API – The Fool Feb 11 '22 at 23:37

1 Answers1

2

To connect the backend with the front through ReactJS, you can use axios to consume an external API, for that you install it in your application:

npm install axios

or

yarn install axios

with the backend application running locally on port 3333, for example, you can create an api.js file in your application and put the code:

import axios from "axios";

const api = axios.create({
  baseURL: "http://localhost:3333/",
});

export default api;

So you can go to your React app's main file and consume using the useEffect hook like this:

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

export default function App() {

  useEffect(() => {
    api
      .get("/YOUR ENDPOINT")
      .then((response) => console.log(response.data))
      .catch((err) => {
        console.error("error" + err);
      });
  }, []);

  return (
    <div className="App">
 
    </div>
  );
}