0
votes

I am using http dependency in angularjs and setting headers for CORS but still getting following error. Please go through console.log you will see following error.

XMLHttpRequest cannot load https://blockchain.info/tobtc?currency=INR&value=1000&cors=true. 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:8080' is therefore not allowed access.

If you go through by this URL, you will get to know that it allows CORS https://blockchain.info/api/exchange_rates_api

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">




<input type = "button" id ="btcButton" value = "Convert" ng-click= "currencytoBtc()" />

</div>

<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope,$http,$q) {

$scope.currencytoBtc = function(){
var a = $scope.currency;
var b = $scope.currencyInput;
console.log(a);
console.log(b);


$http({method: 'GET', url: 'https://blockchain.info/tobtc?currency=INR&value=1000&cors=true', 
            headers:{
                'Access-Control-Allow-Origin': '*',
                'Content-Type': 'text/plain;charset=UTF-8',
                'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
                'Access-Control-Allow-Headers': 'Cache-Control, Pragma, Origin, Authorization,   Content-Type, X-Requested-With' 

             }})
                .then(function(d){ console.log( "yay",d ); })
        .catch(function(d){ console.log( "nope" ); });

}


});





</script>

</body>
</html>
1
the server isn't letting you access it's resources ... by the way, adding those access-control response headers to a request will only ensure that a preflight has to take place - get rid of response headers from your request would be a place to start - Jaromanda X
you need to set the headers in server side. not the client side - Sachila Ranawaka
looking at the response from https://blockchain.info/tobtc?currency=INR&value=1000 looks like they don't send CORS headers, because they don't want you to "borrow" their resources - not sure where you got the idea of adding cors=true request parameter, but it doesn't do anything - Jaromanda X
If you go through by this URL, you will get to know blockchain.info/api/exchange_rates_api - raj

1 Answers

0
votes
Overcoming same-origin policy restrictions with
JSONP
Using JSONP is a trick that allows fetching data by passing the same-origin policy
restrictions. It relies on the fact that browsers can freely pull JavaScript from foreign
servers by using the <script> tag.
JSONP calls don't trigger XHR requests but instead generate a <script> tag whose
source points to an external resource. As soon as a generated script tag appears in the
DOM a browser performs its duty and calls the server. The server pads the response
with a function invocation (thus the "padding" in the name of JSONP technique) in
the context of our web application.
Let's examine a sample JSONP request and response to see how it works in practice.
First of all we need to invoke a JSONP request:
$http
.jsonp('http://angularjs.org/greet.php?callback=JSON_CALLBACK', {
params:{
name:'World'
}
}).success(function (data) {
$scope.greeting = data;
});
Upon invoking the $http.jsonp method AngularJS will dynamically create a new
<script> DOM element like:
<script type="text/javascript" src="http://angularjs.org/greet.
php?callback=angular.callbacks._k&name=World"></script>
Chapter 3
[ 81 ]
As soon as this script tag is attached to the DOM the browser will request the URL
specified in the src attribute. The response, upon arrival, will have a body following
a pattern like:
angular.callbacks._k ({"name":"World","salutation":"Hello","greeting":
"Hello World!"});
A JSONP response looks like a regular JavaScript function call and in fact this exactly
what it is. AngularJS generated the angular.callbacks._k function behind the
scenes. This function, when invoked, will trigger a success callback invocation. The
URL supplied to the $http.jsonp function call must contain the JSON_CALLBACK
request parameter. AngularJS will turn this string into a dynamically generated
function name.
JSONP callback names generated by AngularJS will have a form
of angular.callbacks._[variable]. Make sure that your
back-end can accept callback names containing dots.
JSONP limitations
JSONP is a smart and useful work-around for the same-origin policy restrictions but
it has several limitations. Firstly, we should only GET HTTP requests can be issued
using the JSONP technique. Error handling is also very problematic, since browsers
won't expose HTTP response status from the <script> tag back to JavaScript. In
practice it means that it is rather difficult to reliably report the HTTP status errors
and invoke error callbacks.
JSONP also exposes our web application to several security threats. Apart from
the well-known XSS attack, probably the biggest issue is that a server can generate
any arbitrary JavaScript in the JSONP response. This JavaScript will be loaded
to a browser and executed in the context of a user's session. A server configured
in a malicious way could execute undesired scripts causing different damages,
ranging from simply breaking a page to stealing sensitive data. As such, we should
be really careful while selecting services targeted by JSONP request and only use
trusted servers.