0

i'm trying to fetch an api, but i keep getting this error:

index.html:1 Fetch API cannot load https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1. The 'Access-Control-Allow-Origin' header has a value 'http://null' that is not equal to the supplied origin. Origin 'null' is therefore not allowed access. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Here's the js file including the function attached to the click event on a button:

var header = new Headers({
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'multipart/form-data'
});

function newQuotes(){
  fetch('https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1', {mode: 'cors', header: header})  
  .then(function(response) {
      return response.json();
    })
  .then(function(response) {  
    console.log(response)
  })  
  .catch(function(err) {  
    console.log('Fetch Error', err);  
  });
}

UPDATE I solved the problem by installing this extension Is it te only possible way? Why some people do not have to install it?

Robdll
  • 5,865
  • 7
  • 31
  • 51
  • it works on jsfiddle https://jsfiddle.net/arwvxx40/ – marzelin Jul 23 '17 at 18:37
  • You can not set it in JavaScript, the server has to set and return it. – epascarello Jul 23 '17 at 18:39
  • is it possible to test locally? or via github pages? https://koop4.github.io/random-quote-machine/ – Robdll Jul 23 '17 at 18:46
  • `Access-Control-Allow-Origin` is a **response** header not a request header. quotesondesign.com has to send it to the client, not the other way around. – Quentin Jul 23 '17 at 19:17
  • why did i have to install that extension to make it work? I am trying to read the anwer you provided meanwhile, thanks! – Robdll Jul 23 '17 at 19:22
  • It's a hack that lies to the browser to tell it that the server sent the header. It basically turns off a security feature in your browser that is designed to protect you. – Quentin Jul 23 '17 at 19:24
  • so, the request doesn't have this header, and my browser was refusing the response right? – Robdll Jul 23 '17 at 19:25
  • The browser accepted the response, but refused to give access to it to the JavaScript on the site that triggered the request. – Quentin Jul 23 '17 at 21:37

0 Answers0