简体   繁体   中英

What is best way to connect React to Nodejs backend

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.

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>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM