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 thingPOST
: make a new thingPUT
: change a thingDELETE
: 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.
- You aren't making a
GET
request. This is more specific to Fetch API as it assumesGET
by default so you need to specify in the options that you are usingmethod: "POST"
. - You are, by definition, sending data. Therefore, you must include that data in the method:
body: myData
- 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
Watch for Object Properties Changes in JavaScript
What Are Alternatives to Extjs
How to Format a Date in Mm/Dd/Yyyy Hh:Mm:Ss Format in JavaScript
Chrome Extension: Get Page Variables in Content Script
How to Serve a File for Download with Angularjs or JavaScript
In Bootstrap Open Enlarge Image in Modal
How to Use Preload.Js Properly in Electron
Background-Color Hex to JavaScript Variable
Javascript: Find Longest Word in a String
Share Variables Between Files in Node.Js
Group by Array and Add Field and Sub Array in Main Array
Node.Js Async/Await Using with MySQL
Google Bar Chart Cannot Change Individual Bar Color
How to Set a Cookie with Expire Time
Switch Case Not Showing Correct Results