http post fetch code example
Example 1: javascript fetch api post
fetch('https://example.com/profile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
'foo': 'bar'
}),
})
.then((res) => res.json())
.then((data) => {
})
.catch((err) => console.log(err));
Example 2: react post request
componentDidMount() {
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 }));
}
Example 3: post fetch call
async function postData(url = '', data = {}) {
const response = await fetch(url, {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
referrerPolicy: 'no-referrer',
body: JSON.stringify(data)
});
return response.json();
}
postData('', )
.then(data => {
console.log(data);
});
Example 4: fetch api javascript
fetch('https://apiYouWantToFetch.com/players')
.then(response => response.json())
.then(players => console.log(players))
Example 5: .fetch method
fetch('http://example.com/data.json')
.then(data => data);
.catch(err => console.log(err));