Hello friends, welcome back to my blog. Today in this blog post, I am going to tell you, How to save Reactjs Form Data in Nodejs 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 bootstrap, axios module into our reactjs application:
npm install axios //API Service npm i bootstrap //add bootstrap 5 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, { Component } from 'react'; import axios from 'axios'; import 'bootstrap/dist/css/bootstrap.min.css'; class Create extends Component { constructor(props) { super(props); this.state = { bookID: '', bookTitle: '', bookAuthor: '', data: [], }; } handleInputChange = e => { this.setState({ [e.target.name]: e.target.value, }); }; handleSubmit = e => { e.preventDefault(); const { bookID, bookTitle, bookAuthor } = this.state; const book = { bookID, bookTitle, bookAuthor, }; axios .post('http://localhost:3001/create', book) .then(() => console.log('Book Created'), this.callAPI(); ) .catch(err => { console.error(err); }); }; callAPI() { //API request axios.get("http://localhost:3001/home").then(response => { //getting and setting api data into variable this.setState({ data : response.data }); }) } render() { return ( <div> <br /> <div className="container-fluid p-5 bg-primary text-white text-center"> <h1>How to save Reactjs Form Data in Nodejs Backend?</h1> <p>Therichpost.com is the best tutorial site</p> </div> <div className="container mt-5"> <form onSubmit={this.handleSubmit}> <div className="form-group mb-3"> <input type="text" className="form-control" name="bookID" placeholder="Book ID" onChange={this.handleInputChange} /> </div> <div className="form-group mb-3"> <input type="text" className="form-control" name="bookTitle" placeholder="Book Title" onChange={this.handleInputChange} /> </div> <div className="form-group mb-3"> <input type="text" className="form-control" name="bookAuthor" placeholder="Book Author" onChange={this.handleInputChange} /> </div> <button className="btn btn-success" type="submit"> Create </button> </form> <h3 className="mt-3">Book Details:</h3> <table className="table table-bordered table-striped"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Title</th> <th scope="col">Author</th> </tr> </thead> <tbody> {this.state.data.map((result) => { return ( <tr> <td>{result.BookID}</td> <td>{result.Title}</td> <td>{result.Author}</td> </tr> )})} </tbody> </table> </div> </div> ); } } export default Create;
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 cors = require('cors'); const app = express(); //use cors to allow cross origin resource sharing app.use( cors({ origin: 'http://localhost:3000', credentials: true, }) ); app.use(express.json()); app.use(express.urlencoded({ extended: false })); let books = []; app.post('/create', function(req, res) { const newBook = { BookID: req.body.bookID, Title: req.body.bookTitle, Author: req.body.bookAuthor, }; books.push(newBook); console.log(books); }); app.get('/home', function(req, res) { console.log('Inside Home Login'); res.writeHead(200, { 'Content-Type': 'application/json', }); console.log('Books : ', JSON.stringify(books)); res.end(JSON.stringify(books)); }); //start your server on port 3001 app.listen(3001, () => { console.log('Server Listening on port 3001'); });
5. Now friends, we need open new terminal inside ‘nodeproject’ and need to run with below commands to run node file:
npm init -y npm install express --save npm i cors 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
I am getting a POST 404 error when I axios.post instead axios.get. Any solution