Axios and Fetch both result in CORS error but Postman doesn't

左心房为你撑大大i 提交于 2020-01-25 05:25:06

问题


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>


来源:https://stackoverflow.com/questions/54011655/axios-and-fetch-both-result-in-cors-error-but-postman-doesnt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!