Reputation: 57
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
Upvotes: 4
Views: 11191
Reputation: 707876
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>
Upvotes: 5
Reputation: 3170
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:
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);
});
Upvotes: 5