简体   繁体   English

Axios 和 Fetch 都会导致 CORS 错误,但 Postman 不会

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

If I make a ajax request using either Axios or Fetch to this public endpoint:如果我使用 Axios 或 Fetch 向此公共端点发出 ajax 请求:

http://api.flickr.com/services/feeds/photos_public.gne?format=json 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.但是如果我使用 Postman 发出相同的请求,我可以很好地看到结果。 How to fix this?如何解决这个问题?

Its not an issue of postman vs axios or fetch.这不是邮递员与 axios 或 fetch 的问题。 The issue is the server is returning jsonp not json.问题是服务器返回的是 jsonp 而不是 json。 Neither Axios nor Fetch support jsonp. Axios 和 Fetch 都不支持 jsonp。

Why not use ajax here?为什么不在这里使用ajax?

 $(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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM