如何在 fetch/axios 跨站请求中使用 JSONP

How to use JSONP on fetch/axios cross-site requests(如何在 fetch/axios 跨站请求中使用 JSONP)

本文介绍了如何在 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,但是我在尝试更改时没有成功以 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在 fetch/axios 跨站请求中使用 JSONP

基础教程推荐