In React JS, you can use the fetch()
function to send HTTP requests and to retrieve data from a server or a database. The fetch()
function is a modern and flexible way to make network requests in JavaScript, and it is supported by most modern web browsers.
To send a GET request in React JS, you can use the fetch()
function with the URL of the resource you want to retrieve, and specify the method as ‘GET’. For example:
fetch('https://example.com/api/users', {
method: 'GET'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
This code sends a GET request to the ‘https://example.com/api/users‘ URL and logs the response data to the console. The response.json()
method is used to parse the response data as JSON, and the then()
and catch()
methods are used to handle the success and error cases, respectively.
To send a POST request in React JS, you can use the fetch()
function with the URL of the resource you want to create or update, and specify the method as ‘POST’. You can also specify the data you want to send in the request body using the body
property of the options object. For example:
const data = { name: 'John', age: 30 };
fetch('https://example.com/api/users', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
This code sends a POST request to the ‘https://example.com/api/users‘ URL with the data object as the request body, and logs the response data to the console. The JSON.stringify()
function is used to convert the data object to a JSON string, and the Content-Type
header is set to ‘application/json‘ to indicate that the request body is in JSON format.
Overall, the fetch()
function is a convenient and flexible way to make HTTP requests and to retrieve data in React JS. Whether you need to send a GET request to retrieve data or a POST request