Hi i am trying to write an angular factory to use data from the random.org web api. I am using angular without JQuery. My app fails on loading data from the web service signaling some CORS errors, the code i use is shown below. Any input is appreciated:
'use strict';
angular.module('TrueDice.services', [])
/**
* A simple example service that returns some data.
*/
.factory('TrueRandomService', function ($http) {
var xsrf=({
'jsonrpc': '2.0',
'method': 'generateIntegers',
'params': {
'apiKey': 'd2319b89-8389-4d24-b1eb-4dbd80009153',
'n': 1,
'min': 1,
'max': 6,
'replacement': true,
'base': 10
},
'id': 27846
});
return{
getRand: function (numberOfDices) {
return $http({
url: 'https://api.random.org/json-rpc/1/invoke',
method: 'POST',
headers:{'Content-Type':'application/json-rpc'},
data: xsrf
});
}
};
});
The error is:
XMLHttpRequest cannot load https://api.random.org/json-rpc/1/invoke. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
The angular app is housed in Cordova with the config:
<access origin="*" />
The API at https://api.random.org/json-rpc/1/invoke
is not responding with header Access-Control-Allow-Headers: accept, content-type
. Therefore the browser is rejecting the CORS request.
You can work-around the issue by using a CORS proxy. There are several projects out there you can use for testing (e.g. cors-anywhere comes as a npm module).
I prepared a demo which shows it in action.
The proxy forwards your request to the target and adds the required CORS headers to the response so that the browser stops complaining. When you take a look at the response headers from the proxy you will recognize:
Access-Control-Allow-Headers:accept, content-type
Access-Control-Allow-Methods:POST
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:location,x-request-url,x-final-url