AngularJS consume RESTful in different domains

1

Good afternoon, I'm trying to make a client that indexes the information of several webservices (about bitcoin quotes from several brokers), but when trying to access the webservice the imported json values are not displayed, and pressing F12 in chrome returns the following error message:

  

XMLHttpRequest can not load link . In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' link ' is therefore not allowed access.

I have already researched the error, the same also happens on my remote test server (hostinger), I know the error occurs because the server does not return the header "Access-Control-Allow-Origin = *" are many different third party servers that I will fetch and all return this same error to me ...

follows the code used to access WS: (service)

app.factory('foxbit', ['$http', 
function($http){	
	return $http.get('https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC')
	.success(function(data) {
	  return data;
	})
	.error(function(err) {
	  return err;
	});
}]);

Controller:

app.controller('MainController', ['$scope', 'foxbit', function($scope, foxbit) {
  foxbit.success(function(data) {
    $scope.cotacaofox = data;
  });
  
}]);

So if the ninjas here can point me to a way around this error, I'll be very grateful.

Thank you.

    
asked by anonymous 09.12.2015 / 17:30

1 answer

4

This is a limitation imposed by CORS. Two possibilities:

  • Request blinktrade.com service maintainers to include their source domain in the list of authorized domains, or
  • Implement a local proxy service, eliminating CORS evaluation.

An example of proxy in C # / WebApi 2 comes next:

[RoutePrefix("stack/proxy")]
public class ProxyController : ApiController
{
    [Route("")]
    [HttpGet]
    public object Search([FromUri] string url)
    {
        try
        {
            var client = new HttpClient();
            var result = client.GetStringAsync(url).Result;

            var resp = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain")
            };

            return resp;
        }
        catch (Exception e)
        {
            throw;
        }
    }
}

Usage:

  

>

Result:

{
"high":1693.88,
"vol":248.24057349,
"buy":1623.55,
"last":1623.54,
"low":1551.01,
"pair":"BTCBRL",
"sell":1625.11,
"vol_brl":403631.3524226
}

Source code for WebApi controller removed from the Nyan project (gitHub) .

    
09.12.2015 / 18:34