CORS header ‘Access-Control-Allow-Origin’ missing

2019-07-22 12:50发布

问题:

This question already has an answer here:

  • Does Wikipedia API support CORS or only JSONP available? 1 answer

I'm trying to fetch data from the Wikipedia API with axios in reactJS. This is my get request

axios.get('https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?')
     .then((response) => {
       console.log(response);
     })
    .catch((error)=>{
       console.log(error);

    });

I got this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://en.wikipedia.org/w/api.php?action=opensearch&search=lol&format=json&callback=?. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

Then I changed my start script to:

HTTPS=true yarn start

My server started in https but the error still persists. I have also tried changing json to jsonp as suggested in other threads but it doesn't seem to help as well.

回答1:

You need to add origin=* to the Wikipedia API query parameters:

axios.get('https://en.wikipedia.org/w/api.php?origin=*&action=opensearch&search=lol')
     .then((response) => {
       console.log(response);
     })
    .catch((error)=>{
       console.log(error);
    });
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

For background, see the answer at Does Wikipedia API support CORS or only JSONP available?.