I know that with the new Fetch API (used here with ES2017's async
/await
) you can make a GET request like this:
async getData() { try { let response = await fetch('https://example.com/api'); let responseJson = await response.json(); console.log(responseJson); } catch(error) { console.error(error); } }
But how do you make a POST request?
The fetch() method: Fetch API comes with a fetch () method that allows you to fetch data from all sorts of different places and work with the data fetched. It allows you to make an HTTP request, i.e., either a GET request (for getting data) or POST request (for posting data).
To make a POST request to an API endpoint, you need to send an HTTP POST request to the server and specify a Content-Type request header that specifies the data media type in the body of the POST request. The Content-Length header indicates the size of the data in the body of the POST request.
You tell fetch() to go to a URL by passing it an argument, e.g. fetch("https://flatironschool.com") , and it makes a network request. You chain calls to fetch() with then() . Each then() call takes a callback function as its argument.
In the first line we use the global fetch() function to send a GET request to our API. The argument of fetch() is the URL with the server-side resource. We then chain the promise with the then() method, which captures the HTTP response in the response argument and call its json() method.
Long story short, Fetch also allows you to pass an object for a more personalized request:
fetch("http://example.com/api/endpoint/", { method: "post", headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, //make sure to serialize your JSON body body: JSON.stringify({ name: myName, password: myPassword }) }) .then( (response) => { //do something awesome that makes the world a better place });
Check out the fetch documentation for even more goodies and gotchas:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Please note that since you're doing an async try/catch pattern, you'll just omit the then()
function in my example ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With