javascript fetch no-cors code example
Example 1: Add no cores to fetch
const data = { funny: "Absolutely not", educational: "yas" }
fetch('https://example.com/api/', {
method: 'POST',
mode: 'no-cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then(returnedData => {
}).catch(err => {
})
Example 2: fetch api javascript
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((myJson) => {
console.log(myJson);
});
Example 3: et the request's mode to 'no-cors' to fetch the resource with CORS disabled
var proxyUrl = 'https://cors-anywhere.herokuapp.com/',
targetUrl = 'http://catfacts-api.appspot.com/api/facts?number=99'
fetch(proxyUrl + targetUrl)
.then(blob => blob.json())
.then(data => {
console.table(data);
document.querySelector("pre").innerHTML = JSON.stringify(data, null, 2);
return data;
})
.catch(e => {
console.log(e);
return e;
});
Example 4: javascript cors error
$.ajax({
headers: { "Accept": "application/json"},
type: 'GET',
url: 'http://cl.ly/2wr4',
crossDomain: true,
beforeSend: function(xhr){
xhr.withCredentials = true;
},
success: function(data, textStatus, request){
console.log(data);
}
});
Example 5: fetch suntax
fetch('http://example.com/movies.json')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});