Angularjs consume Restful in different domains

Asked

Viewed 487 times

1

Good afternoon, I am trying to make a client that indexes the information of various webservices (on bitcoin quotes from various brokers) but when trying to access the webservice the values imported from json are not displayed, and pressing F12 on Chrome returns the following error message:

Xmlhttprequest cannot load https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC. No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost' is therefore not allowed access.

have already given a search on the error, the same tbm occurs on my remote test server (Hostinger), I know the error occurs because the server does not return the header "Access-Control-Allow-Origin = *" however are many different third party servers that I will fetch and all return me this same error...

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 mistake,.

Thank you.

  • Have you tried creating a virtual host to see if you can get around the problem? Tip: Don’t leave succes and error in Factory. You should treat this in the controller. And instead of using these functions to handle the return, use 'then'. The two above seem to be 'deprecated'.

  • The problem of the virtual host is that I will put the page on a remote server that does not have access to this customization on the remote server, and as for the Success and the error, I put only pq is easier, but I intend to put it into production..

1 answer

4


This is a limitation imposed by CORS. Two possibilities:

  • Ask the 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;
        }
    }
}

Use:

http://localhost:49801/stack/proxy/? url=https://api.blinktrade.com/api/v1/BRL/ticker?crypto_currency=BTC

Upshot:

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

Webapi controller source code taken from Nyan project (github).

  • Like I said above, I can’t ask the WS maintainers to add the treatment to the Response header...

  • 1

    Hence the suggestion to implement a local proxy service, Dennis. CORS only influences XHR requests between domains. A proxy call acts as a direct request.

  • @Dennis An alternative is to make the requisitions using jsonp. This functionality applies only to Get and internally creates a script element that can reference another domain. An additional parameter will be required to enable the injection of callback. Please search the documentation. $Http.jsonp

  • The JSONP problem is that in the WS I am consuming none of them returns the data in JSONP only in JSON.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.