How can I send data from a react form to a node?
import React from "react"; import "./styles.scss"; const ContactInfo = () => { return ( <div> <h3 className="title">Contact Information</h3> <p className="styles_description__1_Obh"> Please take a moment to verify your contact information. </p> <div className="styles_stepsContainer__isWtJ"> <div className="styles_stepLabel__3f9GG"> <span className="on"></span> </div> <div className="styles_stepLabel__3f9GG"> <span className="off"></span> </div> <div className="styles_stepLabel__3f9GG"> <span className="off"></span> </div> </div> <form className="contact"> <div className="flex"> <div className="form-e m-50"> <label>First Name</label> <input type="text" /> </div> <div className="form-e m-50"> <label>Last Name</label> <input type="text" /> </div> </div> <div className="form-e m-100"> <label>Email Address</label> <input type="email" /> </div> <div className="flex"> <div className="form-e m-50"> <label>DayTime Phone </label> <input type="text" /> </div> <div className="form-e m-50"> <label>Evening Phone </label> <input type="text" /> </div> </div> <button type="submit" className="btn-form"> enviar </button> </form> </div> ); }; export default ContactInfo;
Here you can see a simple post request example in react
import React, { Fragment, useState } from "react";
const InputTodo = () => {
const [description, setDescription] = useState("");
const onSubmitForm = async e => {
e.preventDefault();
try {
const body = { description };
const response = await fetch("http://localhost:4000/todos", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
window.location = "/";
} catch (err) {
console.error(err.message);
}
};
return (
<Fragment>
<h1 className="text-center mt-5">Todo List</h1>
<form className="d-flex mt-5" onSubmit={onSubmitForm}>
<input
type="text"
className="form-control"
value={description}
onChange={e => setDescription(e.target.value)}
/>
<button className="btn btn-success">Add</button>
</form>
</Fragment>
);
};
export default InputTodo;
Sending Data to server
The following example is using post call to create a post in a free api in jsonplaceholder. In this example, we use handleChange for every input element's onChange event like onChange={handleChange}. In handleChange, we are setting post (via useState) of previous all post property using spread operator like...post and update current input element's value using [name]: value} . Then we call post api using axios to update the post record.
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function PostCreate() {
const [post, setPost] = useState({});
const handleChange = ({target}) => {
const {name, value} = target;
setPost({...post, [name]: value});
console.log(post);
};
const handleSubmit = async e => {
e.preventDefault();
const createData = async () => {
try {
const response = await axios.post(`https://jsonplaceholder.typicode.com/posts`, {
method: 'POST',
body: JSON.stringify({
title: post.title,
body: post.body,
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
};
createData();
};
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Title</label>
<input type="text" name='title' value={post.title} onChange={handleChange}
className="form-control" id="title"/>
</div>
<div className="form-group">
<label htmlFor="position">Body</label>
<input type="text" name='body' value={post.body}
onChange={handleChange} className="form-control" id="body"/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default PostCreate;
Here we update data using put call:
import React, {useState, useEffect} from 'react';
import axios from 'axios';
function PostUpdate() {
const [post, setPost] = useState({});
const id = 1;
const handleChange = ({target}) => {
const {name, value} = target;
setPost({...post, [name]: value});
console.log(post);
};
const handleSubmit = async e => {
e.preventDefault();
const updateData = async () => {
try {
const response = await axios.put(`https://jsonplaceholder.typicode.com/posts/${id}`, {
method: 'PUT',
body: JSON.stringify({
id: id,
title: post.title,
body: post.body,
userId: 1
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => response.json())
.then(json => console.log(json));
console.warn(response.data);
} catch (error) {
console.warn(error);
}
};
updateData();
};
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="name">Title</label>
<input type="text" name='title' value={post.title} onChange={handleChange}
className="form-control" id="title"/>
</div>
<div className="form-group">
<label htmlFor="position">Body</label>
<input type="text" name='body' value={post.body}
onChange={handleChange} className="form-control" id="body"/>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default PostUpdate;
Receiving Data from server
In the following example, we are getting all posts from api:
import React, {useEffect, useState} from "react";
import Loader from "./Loader";
import axios from 'axios';
function PostPage() {
const [posts, setPost] = useState([]);
const [isLoading, setIsLoading] = useState(false);
let signal = axios.CancelToken.source();
useEffect(() => {
setIsLoading(true);
let isSubscribed = true;
axios.get(`https://jsonplaceholder.typicode.com/posts`, {
cancelToken: signal.token,
})
.then(res => {
const posts = res.data;
setPost(posts);
setIsLoading(false);
}).catch(err => {
setIsLoading(false);
console.log(err);
});
return function cleanup() {
isSubscribed = false;
signal.cancel('Api is being canceled');
}
}, []);
return (
<React.Fragment>
<ul>
{
isLoading ?
<Loader css='margin-left: 48%; margin-top: 10%' loading={isLoading}/> :
posts.map(post => <li key={post.id}>{post.title}</li>)
}
</ul>
</React.Fragment>
);
}
export default PostPage;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.