const post = async (url, params) => {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(params),
headers: {
'Content-type': 'application/json; charset=UTF-8',
}
})
const data = await response.json()
return data
}
// Then use it like so with async/await:
(async () => {
const data = await post('https://jsonplaceholder.typicode.com/posts', {
title: 'This will be the title',
body: 'Setting the body property',
userId: 1
})
console.log(data)
})()
// Or using then:
post('https://jsonplaceholder.typicode.com/posts', {
title: 'This will be the title',
body: 'Setting the body property',
userId: 1,
}).then(data => console.log(data))
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter