如何在Fetch/Axios跨站点请求上使用JSONP [英] How to use JSONP on fetch/axios cross-site requests

查看:314
本文介绍了如何在Fetch/Axios跨站点请求上使用JSONP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对Wikipedia API进行GET请求.如下使用jQuery可以正常工作:

I'm trying to do a GET request on wikipedia API. Using jQuery as below works fine:

$.ajax({
  url: 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=Test&callback=JSON_CALLBACK',
  type: 'GET',
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  crossDomain: true,
  dataType: 'jsonp'
}).done(function(data) {
  console.log("Data: ", data);  
});

但是我想使用fetch或axios api,它们会以 pre-flight 的请求方法停止运行: OPTIONS .为什么它可以在jQuery中工作,但不能在其他API中工作?

But I want to use fetch or axios api, which stops at pre-flight with request method: OPTIONS. Why it works in jQuery but not in the other APIs?

axios.get('https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=Test&callback=JSON_CALLBACK', 
    { headers: {'X-Requested-With': 'XMLHttpRequest',
                'content-type': 'text/plain'}
    })
    .then(function (response) {
        console.log("Response: ", response);  
    });

我看到它可能与GET请求的Content-Type有关,在jQuery上,默认值似乎是 text/plain ,但是在尝试更改GET时我没有成功以 text/html 发送的fetch/axios请求的内容类型.

I saw that it might be related to the Content-Type of the GET request, on jQuery the default seems to be text/plain, however I didn't have success when trying to alter the content-type of fetch/axios requests which are being sent as text/html.

对可能是什么问题有任何想法吗?

Any thoughts on what might be the problem?

推荐答案

我发现问题与请求的内容类型无关.

I found that the problem is not related to the content-type of the requests.

该问题是由于以下事实造成的:API(获取和axios)不支持 jsonp 请求. jsonp 的使用对我来说还不够清楚,我可以在这里找到很好的解释: http://stackoverflow.com/a/6879276/4051961

The problem was due to the fact that the APIs (fetch and axios) does not support jsonp requests. The use of jsonp was not clear enough for me, I could find a good explanation here: http://stackoverflow.com/a/6879276/4051961

尽管他们不支持它,但它们提供了执行 jsonp 请求的替代方法:

Although they don't support it, they offers alternatives to perform jsonp requests:

axios: https://github.com/mzabriskie/axios /blob/master/COOKBOOK.md#jsonp
获取: https://www.npmjs.com/package/fetch-jsonp

这篇关于如何在Fetch/Axios跨站点请求上使用JSONP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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