Fetch API
- The
fetch()
method is modern and versatile.
- It’s not supported by old browsers (can be polyfilled), but very well supported among the modern ones.
- First, the promise, returned by fetch, resolves with an object of the built-in Response class as soon as the server responds with headers.
- Second, to get the response body, you need to use an additional method call.
Syntax
let promise = fetch(url, [options])
Fetch using Promises
fetch(url)
.then(response => response.json())
.then(data => console.log(data));
Fetch using Async Await
let response = await fetch(url);
let data = await response.json();
console.log(data);
Get JSON Data
async function loadData() {
const response = await fetch("/contents/countries.json");
console.log("resp", response);
if(response.ok) {
const data = await response.json();
console.log("data", data);
}
else
{
console.log("error", response.status);
}
}
Load Image
async function loadImg() {
let response = await fetch('/contents/rose@1x.jpg');
let blob = await response.blob(); // download as Blob object
let img = document.createElement('img');
document.body.append(img);
img.src = URL.createObjectURL(blob);
}
let response = fetch(url, {
headers: {
Authentication: 'secret'
}
});
response.headers.get('Content-Type')
- When submitting form with method
POST
, default enctype
is set to application/x-www-form-urlencoded
. This sets the request header Content-Type
- For submitting form with file, use
POST
method and enctype
should be set to multipart/form-data
Get with params
var url = new URL('https://localhost:7154/Form/Register')
var params = {fname:"ganesh", lname:"kumar"};
url.search = new URLSearchParams(params).toString();
const resp = await fetch(url);
const result = await resp.text();
alert(result)
Post with params
- Using
application/x-www-form-urlencoded
var params = {fname:"ganesh", lname:"kumar"};
fetch('https://localhost:7154/Form/Register', {
method: 'POST',
headers:{
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams(params)
});
Post using JSON
fetch('https://localhost:7154/Form/Register', {
method: 'POST',
body: JSON.stringify({
fname: 'ganesh',
lname: 'kumar'
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
Post Image in JSON
<input type="file" onchange="readFile(this)">
<script>
let imgData;
function readFile(input) {
let file = input.files[0];
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function() {
imgData = reader.result;
};
reader.onerror = function() {
console.log(reader.error);
};
}
function submitData(){
fetch('https://localhost:7154/Form/Register', {
method: 'POST',
body: JSON.stringify({
fname: 'ganesh',
lname: 'kumar',
avatar: imgData
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
}
</script>
Post with multiform-data
let response = await fetch('/form/register', {
method: 'POST',
body: new FormData(form1)
});
let result = await response.text();
alert(result);
Post with multiform-data images
<form id="form1">
<div>Firstname<input type="text" name="fname"></div>
<input type="file" name="avatar" id="avatar">
<button type="submit">Submit</button>
</form>
let response = await fetch('/form/register', {
method: 'POST',
body: new FormData(form1)
});
let result = await response.text();
alert(result);
var formData = new FormData();
formData.append('fname', 'ganesh');
formData.append('lname', 'kumar');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);