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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43471288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:19:56  来源:igfitidea点击:

How to use JSONP on fetch/axios cross-site requests

jqueryajaxfetchaxios

提问by Luan Scudeler

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

我正在尝试对维基百科 API 执行 GET 请求。使用 jQuery 如下工作正常:

$.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);  
});

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

但我想使用 fetch 或 axios api,它在飞行前使用请求方法停止:OPTIONS。为什么它适用于 jQuery 而不适用于其他 API?

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);  
    });

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.

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

Any thoughts on what might be the problem?

关于可能是什么问题的任何想法?

回答by Luan Scudeler

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

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

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

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

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

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

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

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

回答by DominikAngerer

Recommended way to access JSONP with axios is actually to not use axios:

使用 axios 访问 JSONP 的推荐方式实际上是不使用 axios:

  1. The Discussion on Why (not)
  2. A similar question

  3. Alternative Suggestion from Axios

  1. 关于为什么(不)的讨论
  2. 一个类似的问题

  3. Axios 的替代建议

In short install:

简而言之安装:

npm install jsonp --save

use it like:

像这样使用它:

var jsonp = require('jsonp');

jsonp('http://www.example.com/foo', null, function (err, data) {
  if (err) {
    console.error(err.message);
  } else {
    console.log(data);
  }
});

回答by CryptoRuff

Ran into the problem in a React Application

在 React 应用程序中遇到问题

Axios doesn't support JSONP they offers alternatives to perform jsonp requests:

Axios 不支持 JSONP,他们提供了执行 jsonp 请求的替代方法:

Follow this link to see some documentation for jsonp for axios: axios: https://github.com/mzabriskie/axios/blob/master/COOKBOOK.md#jsonp

按照此链接查看 axios 的 jsonp 的一些文档: axios: https://github.com/mzabriskie/axios/blob/master/COOKBOOK.md#jsonp

Here is my documentation:

这是我的文档:

Step 1: $ npm install jsonp --save

第1步: $ npm install jsonp --save

Step 2:

第2步:

import jsonp from 'jsonp';

(this goes at the top of your component)

(这位于组件的顶部)

Step 3: Create a method in your React Component:

第 3 步:在 React 组件中创建一个方法:

JSONP () {
        jsonp( "https://*YourUrlHere.jsonp", { name: 'Name Of JSONP Callback Function' }, (error, data) => {
            if (error) {
                this.setState({
                    error,
                });
            } else {
                this.setState({
                    data: data,
                });
            }
        });
    }