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

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

问题描述

我正在尝试对维基百科 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,它在 飞行前 使用请求方法: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,但是在尝试更改作为 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(fetch 和 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天全站免登陆