componentDidMount() {
// Simple POST request with a JSON body using fetch
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'React POST Request Example' })
};
fetch('https://jsonplaceholder.typicode.com/posts', requestOptions)
.then(response => response.json())
.then(data => this.setState({ postId: data.id }));
}
const handler = () => {
const requestOptions = {
mode: 'no-cors' as RequestMode,
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ "logo": "t-shirt" })
};
fetch('http://localhost:8080/tshirt/19', requestOptions)
.then(response => response.json())
.then(data => setApiData({ postId: data.id }));
}
import axios from "axios";
import React from "react";
const baseURL = "https://jsonplaceholder.typicode.com/posts";
export default function App() {
const [post, setPost] = React.useState(null);
React.useEffect(() => {
axios.get(`${baseURL}/1`).then((response) => {
setPost(response.data);
});
}, []);
function createPost() {
axios
.post(baseURL, {
title: "Hello World!",
body: "This is a new post."
})
.then((response) => {
setPost(response.data);
});
}
if (!post) return "No post!"
return (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
<button onClick={createPost}>Create Post</button>
</div>
);
}