Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, How to use Reactjs as frontend and Nodejs as backend?
For reactjs new comers, please check the below link for basic understanding:
Here is the working code snippet for How to use Reactjs as frontend and Nodejs as backend? and please use carefully and avoid mistakes:
1. Firstly friends we need reactjs fresh setup and for then we need to run below commands into our terminal and also we should have latest node version installed on our pc:
npx create-react-app reactnode cd reactnode npm start
2. Now friends we need to run below commands also to have axios module into our reactjs application:
npm install axios //API Service npm start //start the application
3. Now, we need to add below code into our src/app.js file or you can replace below code with existing one that you have into your src/app.js file:
import React from 'react'; import axios from 'axios'; class Demo extends React.Component { //initialize array variable constructor() { //super is used to access the variables super(); this.state = { data: [] } } componentDidMount() { //API request axios.get("http://localhost:8000/api/cats").then(response => { //getting and setting api data into variable this.setState({ data : response.data.Names }); }) } render() { return ( <div> <h1>therichpost.com</h1> <table> <thead> <tr> <th>Name</th> <th>Position</th> </tr> </thead> <tbody> {this.state.data.map((result) => { return ( <tr> <td>{result.name}</td> <td>{result.position}</td> </tr> )})} </tbody> </table> </div> ) } } export default Demo;
4. Now friends, we need to create new folder name ‘nodeproject’ and inside ‘nodeproject‘ folder create new file name node.js and add below code into it:
const express = require('express'); const app = express(); //I create api route with custom data app.route('/api/cats').get((req, res) => { res.send({ Names: [{ name: 'Therichpost', position: 'Blog' }, { name: 'Ajay Malhotra', position: 'Full Stack Developer' }] }); }); app.listen(8000, () => { console.log('Server started!'); });
5. Now friends, we need open new terminal inside ‘nodeproject’ and need to run with below commands to run node file:
npm install express --save node node.js
Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.
Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements. For better understanding and live working must watch video above.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will good or bad.
Jassa
Thanks
Recent Comments