Axios and Fetch both result in CORS error but Post

2019-07-30 08:18发布

问题:

If I make a ajax request using either Axios or Fetch to this public endpoint:

http://api.flickr.com/services/feeds/photos_public.gne?format=json

I get the following error:

Access to fetch at 'http://api.flickr.com/services/feeds/photos_public.gne?format=json' from origin 'http://localhost:3000' 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.

But if I make the same request using Postman, I can see the results just fine. How to fix this?

回答1:

Its not an issue of postman vs axios or fetch. The issue is the server is returning jsonp not json. Neither Axios nor Fetch support jsonp.

Why not use ajax here?

$(document).ready(function() {
    $.ajax({
        url: 'http://api.flickr.com/services/feeds/photos_public.gne?format=json',
        dataType: 'jsonp',
        jsonpCallback: 'jsonFlickrFeed'
    });
    window.jsonFlickrFeed = function(response) {
    	console.log(response)
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>