How to connect NodeJS with ReactJS ?
NodeJS is primarily used for non-blocking, event-driven servers, due to its single-threaded nature. It’s used for traditional websites and back-end API services but was designed with real-time, push-based architectures in mind.
In this article, we will learn how to connect NodeJS as a backend with ReactJS as a frontend.
- Basic knowledge of React and Node.
- Node.js installed (version 12+).
- npm installed (version 6+).
Project Structure: This is the structure when all the modules and required files are ready.
Backend setup: Firstly we will work on our backend(NodeJS) portion. In your working folder make a file named app.js for NodeJS and package.json file to run all the modules we required.
- Installing ExpressJS is a nodeJS framework:
npm install express
- Installing nodemon:
npm install nodemon
Configuration of package .json file: Add the start and dev script, which are important for running and dynamically running the code after changes made in your Node.js app respectively in package.json file as shown below.
Run the application using the following command:
npm run dev
- This will be a console output.
- Now go to http://localhost:8080/ in your browser, you will see the following output.
Filename- app.js: Now for connecting the React part we have to make some changes in the app.js of NodeJS. We have completed the backend part.
Frontend setup: First, we have to create React app and run your app by writing the below command.
npx create-react-app demo cd demo npm start
Output: Now go to http://localhost:3000/ in your browser, you will see the following output.
Connecting: We have completed both the frontend and backend parts, now we have to connect both. Now for connecting Reactjs with Nodejs we have added this line in package.json of react app folder:
Filename- package.json: The package.json file is in your React app folder. This tells React to proxy API requests to the Node.js server built with Express in our project.
Filename- App.js: Made some changes in app.js of React to show that they are connected.
Now run the Nodejs process npm run dev in one terminal and in another terminal start Reactjs using npm start simultaneously.
Output: We see react output we see a button “Connect” we have to click it. Now when we see the console server-side we see that the ReactJS is connected with NodeJS.