Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST Request with Fetch API?

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?

like image 568
Rob Avatar asked Sep 19 '16 05:09

Rob


People also ask

Can fetch API be used for POST?

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).

How do I do a POST request for an API?

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.

How do I transfer data using Fetch?

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.

Does fetch send a GET request?

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.


1 Answers

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 ;)

like image 153
hellojebus Avatar answered Sep 23 '22 10:09

hellojebus