21

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

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

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?

Luan Scudeler
  • 441
  • 2
  • 5
  • 11

4 Answers4

21

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 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

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

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

Luan Scudeler
  • 441
  • 2
  • 5
  • 11
14

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

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

  3. Alternative Suggestion from 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);
  }
});
DominikAngerer
  • 6,354
  • 5
  • 33
  • 60
5

Ran into the problem in a React Application

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

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

Here is my documentation:

Step 1: $ npm install jsonp --save

Step 2:

import jsonp from 'jsonp';

(this goes at the top of your component)

Step 3: Create a method in your React Component:

JSONP () {
        jsonp( "https://*YourUrlHere.jsonp", { name: 'Name Of JSONP Callback Function' }, (error, data) => {
            if (error) {
                this.setState({
                    error,
                });
            } else {
                this.setState({
                    data: data,
                });
            }
        });
    }
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
CryptoRuff
  • 51
  • 1
  • 1
2

yarn add simple-jsonp-promise or npm install simple-jsonp-promise

import jsonp from 'simple-jsonp-promise'

async function Test () {
  const url = 'http://...'
  const params = {param1: 1, param2: 2}

  const response = await jsonp(url, {data: params})
  console.log('response:', response)
}
TitanFighter
  • 4,582
  • 3
  • 45
  • 73