You can use the fetch()
function to make a POST request after your React website has loaded. Here's an example:
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
fetch('https://example.com/api/submit', {
method: 'POST',
body: JSON.stringify({ name: 'John', age: 30 }),
headers: { 'Content-Type': 'application/json' }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
}, []);
return <h1>Hello World!</h1>;
}
In this example, the useEffect
hook is used to make the POST request when the component is mounted. The empty array []
passed as the second argument ensures that the effect is only run once, when the component mounts. The fetch
function is used to make the POST request, and the data to be sent is provided as the body
option. The headers
option is used to specify that the data is in JSON format. Finally, the response is parsed as JSON and logged to the console.
Asked: 2021-09-15 11:00:00 +0000
Seen: 12 times
Last updated: May 11 '21