EN
React - Ajax POST request
3 points
In this article we would like to show you how to make AJAX POST request in React.
In below example fetch
method were used with two parameters:
- path to backend logic located on server,
- request configuration that let us to configure: request method, request headers, request body, etc.
In below example we used POST
method that alows to send some data in body.
Practical example:
xxxxxxxxxx
1
//import React from 'react';
2
3
const Form = () => {
4
const handleSubmit = async (e) => {
5
e.preventDefault();
6
const elements = e.target.elements;
7
const requestData = {
8
username: elements.username.value,
9
password: elements.password.value,
10
};
11
const requestJson = JSON.stringify(requestData);
12
try {
13
const response = await fetch("/path/to/backend", {
14
method: "POST",
15
body: requestJson,
16
});
17
const responseText = await response.text();
18
console.log(responseText);
19
} catch (ex) {
20
console.error("POST error!");
21
}
22
};
23
return (
24
<form onSubmit={handleSubmit}>
25
<div>
26
<label>Username: </label>
27
<input type="text" name="username" />
28
</div>
29
<div>
30
<label>Password: </label>
31
<input type="password" name="password" />
32
</div>
33
<div>
34
<input type="submit" value="Submit!" />
35
</div>
36
</form>
37
);
38
};
39
40
const root = document.querySelector("#root");
41
ReactDOM.render(<Form />, root);