1

I tried to make a request from wikipedia api. Though I use a normal node.js server (localhost) i get this in the console:

XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&generator=search&piprop=name|original&pilimit=max&gsrsearch=Horse&gsrlimit=20. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

This is my react component:

import React, {Component} from 'react';
import axios from 'axios';

class WikipediaViewer extends Component {

   constructor(props) {
      super(props);
      this.state = {
         data: null
      }
   }

   componentDidMount() {

      axios.get('https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&generator=search&piprop=name|original&pilimit=max&gsrsearch=Horse&gsrlimit=20')
      .then(data => {
            this.setState({
               data: data
            });
            console.log(data);
         })
   }

   render() {
      return (
         <h1>HEllo world!</h1>
      );
   }

}

export default WikipediaViewer

After having issus with the request I add following config options according to the axios documentation:

componentDidMount() {

  axios.get({
     method: 'get',
     url: 'https://en.wikipedia.org/w/api.php?action=query&format=json&prop=pageimages&generator=search&piprop=name|original&pilimit=max&gsrsearch=Horse&gsrlimit=20',
     headers: {'X-Requested-With': 'XMLHttpRequest'},
     withCredentials: true,
  }).then(data => {
        this.setState({
           data: data
        });
        console.log(data);
     })

}

Result:

GET http://localhost:3000/[object%20Object] 404 (Not Found)

Why am I have to get this error, though I'm working locally. Btw I used the "Allow-Control-Allow-Origin: *" Chrome extension from vitcad as well and it doesn't work.

  • See the answer at https://stackoverflow.com/questions/42077084/access-control-allow-origin-with-wikipedia-api-with-javascript/42079398#42079398. You must add `origin=*` to the query params: `url: 'https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&prop=pageimages&generator=search&piprop=name|original&pilimit=max&gsrsearch=Horse&gsrlimit=20'` – sideshowbarker Jul 09 '17 at 09:36
  • See also https://stackoverflow.com/questions/37106041/does-wikipedia-api-support-cors-or-only-jsonp-available/37109743#37109743 for a longer history about this Wikipedia quirk – sideshowbarker Jul 09 '17 at 09:56

0 Answers0