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

查看:38
本文介绍了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?

推荐答案

这不是 postman 与 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天全站免登陆