How to Connect FRONTEND AND BACKEND(React + Node)

How to Connect FRONTEND AND BACKEND(React + Node)

  1. Create a frontend folder

  2. Create a backend folder

Initialize your frontend folder by react project

initialize your backend folder by node/express project

//Frontend
import React, { useEffect, useState } from 'react'
import axios from 'axios';

const App = () => {
  const [data, setData] = useState('');

  const getData=async() =>{
    const response = await axios.get('http://localhost:5000/getData');
    setData(response.data);
  }

  useEffect(()=>{
    getData()
  }, []);


  return (
    <div>{data}</div>
  )
}

export default App
//Backend
import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors());

app.listen(5000,()=>{
    console.log(`Server running at port 5000`);
})

app.get("/getData", (req,res) => {
    res.send("Hello from backend");
})

Function of axios

  1. HTTP Client: Axios is a JavaScript library that helps you make HTTP requests from your browser or Node.js applications.

  2. Simplified Requests: It simplifies the process of making HTTP requests by providing a clean and easy-to-use API.

  3. Cross-Browser Compatibility: Axios works consistently across different browsers, ensuring your application behaves the same way for all users.

  4. Promise-Based: Axios is based on Promises, which allows you to handle asynchronous operations in a more convenient and readable way.

  5. Features: It supports features like request and response interception, automatic JSON data parsing, and the ability to cancel requests.

  6. Popular Choice: Axios is widely used in the JavaScript community because of its simplicity, reliability, and extensive documentation.

Function of cors

CORS is typically enabled on the server-side by configuring web servers to include the necessary CORS headers in responses. This allows clients (browsers) to make cross-origin requests to access resources securely.

Did you find this article valuable?

Support Thirumalai by becoming a sponsor. Any amount is appreciated!