Post Request with Fetch API

Fetch: POST JSON data

With ES2017 async/await support, this is how to POST a JSON payload:

(async () => {  const rawResponse = await fetch('https://httpbin.org/post', {    method: 'POST',    headers: {      'Accept': 'application/json',      'Content-Type': 'application/json'    },    body: JSON.stringify({a: 1, b: 'Textual content'})  });  const content = await rawResponse.json();
console.log(content);})();

How to post body data using Fetch API?

Looking at the curl your data does seem to be URL encoded. So as it's not expecting JSON don't serialize it to a JSON string.

const headers = new Headers({
"Content-Type": "application/x-www-form-urlencoded"
});

const urlencoded = new URLSearchParams({
"grant_type": "password",
"username": "test",
"password": "xyz1234",
"scope": "write",
"client_id": "test",
"client_secret": "test12",
});

const opts = {
method: 'POST',
headers: headers,
body: urlencoded,
};

fetch("https://example.com/access_token", opts);

EDIT

As @Kaiido mentioned in the comments. It is not necessary to set the Content-Type header explicitly as the browser will do that automatically, but I have done it here to show you that it should not be set to application/json but to application/x-www-form-urlencoded.

POST Request with Fetch API?

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

When using the Fetch API, why do post requests require more inputs than a get request?

TLDR, POST has more stuff to it.

GET and POST are methods for HTTP Requests. The main ones of interest are:

  • GET: get a thing
  • POST: make a new thing
  • PUT: change a thing
  • DELETE: delete a thing

The most basic form of a GET is asking a specific URI to send back pre-set data. Also, GET tends to be the most common use request so most HTTP request-making methods will make this very simple. Thus, GET is often done with little more than a URI.

In contrast, POST has a lot going on.

  1. You aren't making a GET request. This is more specific to Fetch API as it assumes GET by default so you need to specify in the options that you are using method: "POST".
  2. You are, by definition, sending data. Therefore, you must include that data in the method: body: myData
  3. Data has a format. The server has no idea if you sent it a string, and integer, a JSON, or the whole Harry Potter movie set. It just sees a stream of 1s and 0s. This is where headers come in, which let you specify to the server that you are sending it a JSON object or an image file so that the server can appropriately deal with the bits. Thus, we see headers: { 'Content-Type': <MIME type of myData> } in the options.

JavaScript POST fetch sends as OPTIONS

thats a preflight request

Handle the options request by passing the correct CORS Headers back.

Then also handle the post request, both of these are needed due to the new CORS standards for APIs and Websites.

Fetch Api is unable to post things to the server

I fixed my problem with a simple line of code. Looks like the client-side code and the server code is all fine. We have also specified headers in the options of the fetch too. The problem was that the server didn't know in which format it could expect data from the client. Thus, adding the following code before the app.post() method will fix this issue.

app.use(express.json());


Related Topics



Leave a reply



Submit