Search code examples
javascriptxmlhttprequestcors

OpenFIGI API and CORS


I'm trying to interface the OpenFIGI API from a browser application, which I am hosting locally by using node's http-server. My POST-request looks like this

  var xhr = new XMLHttpRequest();
  var url = 'https://api.openfigi.com/v1/mapping';
  var params = [{"idType": "ID_WERTPAPIER", "idValue": "851399", "exchCode": "US"}];
  xhr.open('POST', url, true);
  xhr.setRequestHeader("Content-type", "text/json");
  xhr.onreadystatechange = function() {
    console.log(xhr.responseText);
  }
  xhr.send(params);

But all I am getting is the errors

  • Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
  • XMLHttpRequest cannot load https://api.openfigi.com/v1/mapping. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:20000' is therefore not allowed access. The response had HTTP status code 405.

Since I've been trying around with different ways to do the request and different settings, I am wondering - is that even possible? Am I missing something w.r.t. request? I looked at the OpenFIGI API examples, but I could not find any other (CORS) settings there.


Solution

  • OpenFIGI API responses don’t include the Access-Control-* response headers needed to make browsers allow your frontend JavaScript code to access the responses. So if you want to send the requests from your frontend code, your only option is use a proxy.

    To try making the request through a public CORS proxy, try changing your code to:

    var url = 'https://cors-anywhere.herokuapp.com/'
       + 'https://api.openfigi.com/v1/mapping';
    

    That sends the request through https://cors-anywhere.herokuapp.com, which forwards the request to https://api.openfigi.com/v1/mapping and then receives the response. The https://cors-anywhere.herokuapp.com backend then adds the Access-Control-Allow-Origin header to the response and finally passes that back to your requesting frontend code.

    The browser will then allow your frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.

    You can also easily set up your own CORS proxy using https://github.com/Rob--W/cors-anywhere/

    For details about what browsers do when you send cross-origin requests from frontend JavaScript code using XHR or the Fetch API or AJAX methods from JavaScript libraries—and details about what response headers must be received in order for browsers to allow frontend code to access the responses—see https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS.