I tried to use this Cat Facts API like so:
const URL = "https://catfact.ninja/fact?limit=1" // In browser, this displays the JSON
fetch(URL).then(response=> {
console.log(response);
return response.json();
}
);
but I got
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://catfact.ninja/fact?limit=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
TypeError: NetworkError when attempting to fetch resource.
so after trying with
fetch(URL, {mode:'no-cors'})
.then(response=> {
console.log(response);
return response.json();
}
);
I now get
Response { type: "opaque", url: "", redirected: false, status: 0, ok: false, statusText: "", headers: Headers, body: null, bodyUsed: false }
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
I understand from here that I won't be able to use this API as intended. But if so, what is the purpose of it and how is it intended to be used (this info does not account for the issue)?
An opaque response is one you cannot see the content of. They aren't useful in of themselves.
Setting mode: 'no-cors' is a declaration that you don't need to read the response (or do anything else that requires CORS permission).
For example, the JavaScript might be sending analytics data to be recorded by a server.
The benefit of no-cors mode is that it lets you send the data without getting exceptions reported in the JS console (which would (a) look bad if anyone opened it and (b) flood the console with junk that makes it hard to find real errors).
If you need to access the response, don't set mode: 'no-cors'. If it is a cross origin request then you will need to use some other technique to bypass the Same Origin Policy.
Aside: "Access-Control-Allow-Origin": "*" is a response header. Do not put it on a request. It will do nothing useful and might turn a simple request into a preflighted request.
Adding {mode: 'no-cors'} is not a catch-all for CORS errors. You might be better off using a CORS Proxy.
This question might also be of use to you.
Alternatively, and depending on your needs, using a different API could be the easiest solution. I was able to return a cat fact from "https://meowfacts.herokuapp.com/". See below.
const URL = "https://meowfacts.herokuapp.com/"
async function getCatFact() {
const response = await fetch(URL)
console.log(await response.json())
}
getCatFact()
Related
I have tried to use Riot games API, the below code has returned 'Status Code: 200'and seems like ok and then I got two errors as below.
Access to fetch at 'https://oc1.api.riotgames.com/lol/summoner/v4/summoners/by-name/edisona?api_key=RGAPI-xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET https://oc1.api.riotgames.com/lol/summoner/v4/summoners/by-name/edisona?api_key=RGAPI-xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx net::ERR_FAILED
So I added { mode: 'no-cors' } and error is gone, but there is no data that has been returned in the console after that I just use the URL directly and the browser shows the right data. I do not know why it happened, I appreciate if you can help me.
const name = 'edisona';
const api_key = 'RGAPI-xxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx';
const url =
'https://oc1.api.riotgames.com/lol/summoner/v4/summoners/by-name/' +
name +
'?api_key=' +
api_key;
fetch(url)
.then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
This seems like a Cross-Orgin request error (you didn't add CORS headers to the proxied request).
Try using CORS-Anywhere, a NodeJS reverse proxy to do just that.
Here's a demo. Try reading some about CORS: https://fetch.spec.whatwg.org/#cors-protocol-and-credentials
I am trying to get data from an external API from the background script of my Chrome extension, using messaging to initiate the call from the content script and get the results. I have no control over the external API. The documentation from that API says to use script tags to get a jsonp response, but if I understand correctly, that shouldn't matter when the below items are implemented. Am I wrong?
the fetch() is in the background script
"\*://\*/" is in my permissions in the manifest (I will change that if I can get this to work, just eliminating that possibility)
The extension is 'packed'
Error:
Access to fetch at 'https://external-api.com' from origin 'chrome-extension://bunchofchars' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Any clue as to what I'm doing wrong?
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
fetch('https://api.com/' + request.user + 'restofurl',
{
method: 'get',
headers: {'Content-Type':'application/json'}
})
// .then(response => parseResults(response.results))
.then(response => sendResponse({result: response.results}))
// .catch(error => ...)
return true;
});
content.js
(() => {
function foo() {
var parent = document.getElementById('someId');
var username = parent.getElementsByTagName('a')[6].innerHTML;
chrome.runtime.sendMessage({user: username}, function(response) {
console.log(response.result);
});
window.addEventListener('load', foo);
})();
Manifest version 3 uses the host_permissions field
"host_permissions": ["https://api.com/*"],
Maybe your extension is allowed only to read and modify on this particular site.
Let extensions read and change site data
When you click the extension: This setting only allows the extension to access the current site in the open tab or window when you click the extension. If you close the tab or window, you’ll have to click the extension to turn it on again.
On [current site]: Allow the extension to automatically read and change data on the current site.
On all sites: Allow the extension to automatically read and change data on all sites.
Try to change to the last option. This should change CORS policy.
Ideally, cors issue must be resolved on the server-side by adding specific origins. This is because all modern browsers such as chrome block the requests originating from the same machine.
In this case, however, please try to use additional fetch parameters as follows:
fetch(url, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'no-cors', // no-cors, *cors, same-origin
headers: {
//'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
I'm having issues fetching an external API who should return JSON.
The API doesn't have CORS enabled so I'm trying to use fetch with the option mode: "no-cors".
I tried to use jsonp but doesn't work at all.
So here's the piece of code:
fetch(APIURL, {
mode: "no-cors",
}).then(response => {
console.log(response)
return response.json();
}).then(data => {
console.log(data);
}).catch(err => {
console.log(err)
});
The catch statement returns this SyntaxError: "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data"
Here's the result of console.log(response)
bodyUsed: true
headers: Headers
<prototype>: HeadersPrototype { append: append(), delete: delete(), get: get(), … }
ok: false
redirected: false
status: 0
statusText: ""
type: "opaque"
url: ""
<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }
But in the network tab I can see the JSON response that I want to use so I find it weird that I can see it in there so I assume the problem is on my end. I tried validating the JSON output in a validator and it's a valid JSON.
Any Ideas?
Thanks.
Under normal circumstances, you cannot read data from a third party site due to the Same Origin Policy.
CORS allows the third party site to grant your JavaScript permission to read the data.
The no-cors setting is a means for your JavaScript to say "I do not want to do anything that requires permission from CORS". This lets you make a request to send data without being able to read the response (the benefit is that it avoids throwing an error message all over the developer console telling you that you can't read the data you aren't trying to read).
Since you need to read the data, you cannot use no-cors.
Since the site doesn't provide permission with CORS, you cannot read the data directly with client-side code.
Use a proxy.
I'm developing an app with React + Redux and I have my JSON database within a Firebase DB.
To do this I'm tryin to fetch my data from a valid URL (validated from Firebase simulator)
let firebase = 'https://******.firebaseio.com/**/*/***/*'
return (dispatch) => {
return fetch(firebase)
.then(res => res.json())
.then(json => dispatch({ type: 'GET_JSON', payload: json }))
}
This returns to me the error:
Fetch API cannot load https://console.firebase.google.com/project/****/database/data/**/*/***/*. Redirect from 'https://console.firebase.google.com/project//database/data/**///' to 'https://accounts.google.com/ServiceLogin?ltmpl=firebase&osid=1&passive=true…ole.firebase.google.com/project//database/data///**/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.`
I've tried many solutions, like adding to fetch's second argument { mode: 'no-cors', credentials: 'same-origin'}, but when I try this i get Uncaught (in promise) SyntaxError: Unexpected end of input.
What am I missing?
likely error that arise to cors blocked when using firebase is
when you initiate a put or get request with an incomplete firebase url
e.g
// wrong form
this.http.get('https://******.firebaseio.com/data') //this will throw an exception
// correct form
this.http.get('https://******.firebaseio.com/data.json')
I had this problem with a serviceworker implementation of fetch
self.addEventListener('fetch', (e) => {
fetch(e.request) // valid arg && works with firebase
fetch(e.request.url) // valid arg but will cause access-control error!
}
For a simple request to be allowed cross-domain, the server simply needs to add the Access-Control-Allow-Origin header to the response.
Also refer this turorial, if you have any doubts
Cross-Origin XMLHttpRequest
Using CORS.
I'm trying to use window.fetch() to get json from the server, but can't get the data from the response.
I have this code:
let url =
'https://api.flightstats.com/flex/schedules/rest/v1/json/from/SYD/to/MEL/departing/2016/3/28?appId=f4b1b6c9&appKey=59bd8f0274f2ae88aebd2c1db7794f7f';
let request = new Request (url, {
method: 'GET',
mode: 'no-cors'
});
fetch(request)
.then(function(response){
console.log(response)
});
It seems that this request is successfull, I see status 200
and response body with json in network tab - status and response. But in console.log I dont see json object - console log image
I cant understand why I dont see json in console.log
The host site you are requesting from does not appear to support CORS. As such, you can't use fetch() to make a cross origin request and get the data back. If, you change your fetch() request to mode: 'cors', the debug console will show that the host site does not offer CORS headers to allow the browser to show you the result of the request.
When you are using mode: 'no-cors', the browser is hiding the result from you (because you don't have permission to see it) and you can see the response is tagged as opaque.
In a little poking around on the api.flightstats.com site, I did see that it supports JSONP which will allow you to work around the lack of CORS support issue and successfully complete a cross origin request.
For simplicity of showing that it can work, I used jQuery to just prove that a JSONP request can be made. Here's that code in a working snippet. Note I changed the URL from /json/ to /jsonp/ and specific dataType: "jsonp" in the jQuery request. This causes jQuery to add the callback=xxxxx query parameter and to fetch the response via that corresponding script (the JSONP method).
var url =
'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/from/SYD/to/MEL/departing/2016/3/28?appId=f4b1b6c9&appKey=59bd8f0274f2ae88aebd2c1db7794f7f';
$.ajax(url, {dataType: "jsonp"}).then(function(response) {
log(response);
}, function(err) {
log("$.ajax() error:")
log(err);
})
<script src="http://files.the-friend-family.com/log.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you take a look at the documentation of the Fetch API; you'll notice that the API offers various methods to extract the data:
arrayBuffer()
blob()
json()
text()
formData()
Assuming the response is valid JSON (which I've noticed it doesn't seem to appear), you can use the response.json() function to retrieve the response data. This also uses a Promise mechanism, as for everything with the Fetch API.
response.json().then(function(data) {
console.log(data);
});