Axios和Fetch都导致CORS错误,但Postman却没有 [英] Axios and Fetch both result in CORS error but Postman doesn't

查看:112
本文介绍了Axios和Fetch都导致CORS错误,但Postman却没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用Axios或Fetch向此公共端点发出Ajax请求:

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

我收到以下错误:

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.

但是,如果我使用Postman发出相同的请求,我可以看到结果很好.该如何解决?

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

推荐答案

这不是邮递员vs axios或fetch的问题.问题是服务器返回的是jsonp而不是json. Axios和Fetch都不支持jsonp.

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.

为什么不在这里使用ajax?

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>

这篇关于Axios和Fetch都导致CORS错误,但Postman却没有的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆