,

Submitting Form Data to API Using React JS and Node | Tutorial for React CRUD操作

Posted by






Post User Form Data to API with React JS | React CRUD Tutorial with Node

Post User Form Data to API with React JS

In this tutorial, we will learn how to create a user form in a React JS application and then post the form data to an API using a Node server. This tutorial will cover the basics of React JS, how to set up a Node server, and how to perform CRUD operations using React and Node.

Setting up the React Application

First, we need to set up a new React application using create-react-app. Open your terminal and run the following command:

npx create-react-app my-app

Once the application is created, navigate to the project directory and start the development server:

cd my-app
npm start

Your React application should now be running at http://localhost:3000.

Creating the User Form

Now that we have our React application set up, let’s create a simple user form. In the src directory, create a new file called UserForm.js:

touch src/UserForm.js

Open the UserForm.js file and add the following code:

“`javascript
import React, { useState } from ‘react’;

const UserForm = () => {
const [formData, setFormData] = useState({
name: ”,
email: ”,
});

const handleChange = (e) => {
setFormData({ …formData, [e.target.name]: e.target.value });
};

const handleSubmit = (e) => {
e.preventDefault();
// TODO: Post form data to API
};

return (




);
};

export default UserForm;
“`

This code creates a simple user form with input fields for name and email. The form data is managed using the useState hook, and the handleChange and handleSubmit functions handle the form input changes and submission, respectively.

Posting Form Data to API

Now that we have our user form, let’s post the form data to an API using a Node server. We will create a simple API endpoint in Node to handle POST requests for user data.

First, create a new directory for your Node server and navigate to it:

mkdir server
cd server

Then, initialize a new Node project and install the necessary packages:

npm init -y
npm install express body-parser

Create a new file called server.js and add the following code:

“`javascript
const express = require(‘express’);
const bodyParser = require(‘body-parser’);

const app = express();

app.use(bodyParser.json());

app.post(‘/api/users’, (req, res) => {
const { name, email } = req.body;
// TODO: Save user data to database
res.status(201).json({ message: ‘User data saved successfully’ });
});

const port = process.env.PORT || 5000;

app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
“`

This code sets up a basic Node server using Express and creates a POST endpoint at /api/users to handle user data. The server listens on port 5000 by default, but you can change this to any port of your choice.

Now, we need to modify the handleSubmit function in the UserForm.js file to make a POST request to our API endpoint:

“`javascript
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch(‘http://localhost:5000/api/users’, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify(formData),
});
const data = await response.json();
console.log(data.message);
} catch (error) {
console.error(‘Error posting user data:’, error);
}
};
“`

With this code, we are making a POST request to our API endpoint with the form data using the fetch API. We then handle the response from the server and log any error messages to the console.

Conclusion

In this tutorial, we learned how to create a user form in a React JS application and post the form data to an API using a Node server. We covered the basics of React JS, setting up a Node server, and performing CRUD operations using React and Node. Now you can extend this tutorial to include additional CRUD operations, validation, and error handling as needed.


0 0 votes
Article Rating
7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
gagan kanaujia
10 months ago

please explain about if image is also uploaded with data

Md Faisal Raza Khan
10 months ago

what ever I typing in fields, after submission it is adding like http://localhost:3000/?address=hvc&name=srfw in the main URL , how to solve this ?

@zoey.
10 months ago

Thanks for the tutorial . May i ask sir why i can't type in input value .

Priya Kumari
10 months ago

Thanks!

Manju Maurya
10 months ago

Best one

Shuvo Roy
10 months ago

bro es serise ko plz postgreSQL ka stimal kar ki ek video create karo plz….

Shuvo Roy
10 months ago

bro thora kom bolo eha par…. tomhara video bahot acca lakin hum bathot parisan hogi tumhara egapar sunty sunty