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 ;)
JavaScript fetch() with JSON parameter
Your data myFood
already is a JSON string, then no need to cast it to string with JSON.stringify(data)
in postData
function.
A simple way to fix this issue - make sure the data object always be a JSON object.
var myFood = {
"ingredients": [
{
"quantity": 2,
"measureURI": "http://www.edamam.com/ontologies/edamam.owl#Measure_ounce",
"foodId": "food_akjf74ibll2id8aqb8xbha4t4axl",
},
]
}; // object instead of string
Using fetch to post JSON data
you must call your fetch
function in handlesubmit
function...according to this link , componentWillMount : is executed before rendering, on both server and client side.
so your form is empty.
you need read more about react life cycle.
Using fetch to post cross-origin JSON data to Express backend
You can not POST
a plain javascript object.
But, please do check all possible values of Content-type
as defined in RFC 1341 with the list of mime types.
According to MDN
Fetch body data type must match "Content-Type"
header.
Try this code instead.
const form = document.getElementById("myForm");
form.addEventListener("submit", (e) => {
e.preventDefault();
var data = {
firstName: e.target.firstName.value,
lastName: e.target.lastName.value
}
fetch("http://localhost:5000/form-post", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json; charset=utf-8",
},
body: JSON.stringify(data)
})
.then((res) => res.json())
.then((data) => console.log(data));
});
How can I fetch one value type from the JSON data and display in a list?
EDIT (based on comments):
It appears you are going to fetch a REST endpoint, so you can not fetch only parts of a response (as opposed to e.g. graphQL) so all you can do is selectivelly include/exclude data that you need. I updated the code to reflect this.
The code is good but you should always try to code your app with data as close as possible to the real one. Using a data source with a different shape from what you will end up using will always bring in bugs and changes in code.
I updated your example to use the data you provided instead of fetching from the API you were using. Take a look into the nested loop in the updateHTML()
method.
const src = {
"code": "200",
"drawdate": "1 มีนาคม 2564",
"result": [
{
"id": "lotto_one",
"name": "รางวัลที่ 1",
"reword": 6000000,
"amount": 1,
"number": "835538"
},
{
"id": "lotto_first_three",
"name": "เลขหน้า 3 ตัว",
"reword": 4000,
"amount": 2,
"number": [
"290",
"838"
]
},
{
"id": "lotto_last_three",
"name": "เลขท้าย 3 ตัว",
"reword": 4000,
"amount": 2,
"number": [
"051",
"806"
]
},
{
"id": "lotto_last_two",
"name": "เลขท้าย 2 ตัว",
"reword": 2000,
"amount": 1,
"number": "73"
},
{
"id": "lotto_side_one",
"name": "รางวัลข้างเคียงรางวัลที่ 1",
"reword": 2000,
"amount": 1,
"number": [
"835537",
"835539"
]
},
{
"id": "lotto_two",
"name": "รางวัลที่ 2",
"reword": 200000,
"amount": 5,
"number": [
"316827",
"731177",
"743731",
"788652",
"923096"
]
},
]
};
const output = document.querySelector('.output');
/*
// Use local data instead
fetch('https://api.chucknorris.io/jokes/random', {
headers: {
"Content-Type": "application/json",
"x-api-key": "pass",
},
})
.then(response => response.json())
.then(updateHTML);
*/
function updateHTML(data) {
// Get the object entries - and array of key/value pairs
const entries = Object.entries(data);
// Iterate over the entries and return a new array
// of strings created from the key/value using a
// template string.
const rows = data.map((entry) => {
return Object.keys(entry).map((key) => {
let value = entry[key];
if (key === 'number') {
if (Array.isArray(value)) {
value = value.join(' | ');
}
return `
<tr>
<td class="heading">${key}</td>
<td>${value}</td>
</tr>
`;
}
}).join('');
});
// Create a new HTML string by `join`ing up the row array
// and adding it to a new string
const html = `<table><tbody>${rows.join('')}</tbody></table>`;
// Insert the HTML into the page
output.insertAdjacentHTML('beforeend', html);
}
updateHTML(src.result);
<div class="output"></div>
Related Topics
Convert a Unix Timestamp to Time in JavaScript
How to Create and Read a Value from Cookie With JavaScript
How Does the "This" Keyword in JavaScript Act Within an Object Literal
Is JavaScript Guaranteed to Be Single-Threaded
Asynchronous Process Inside a JavaScript For Loop
Detecting an Undefined Object Property
How to Sort an Array of Objects by Multiple Fields
How to Split a String, Breaking At a Particular Character
How to Read a Local Text File in the Browser
Difference Between == and === in JavaScript
How to Create a Two Dimensional Array in JavaScript
Cartesian Product of Multiple Arrays in JavaScript
What Is a Good Regular Expression to Match a Url
Chrome Extension Message Passing: Response Not Sent
Fastest Way to Duplicate an Array in JavaScript - Slice Vs. 'For' Loop
How to Test For an Empty JavaScript Object