簡體   English   中英

AngularJS:CORS問題

[英]AngularJS: CORS issue

我在angularjs中使用http依賴項並為CORS設置標頭,但仍然收到以下錯誤。 請通過console.log,您將看到以下錯誤。

XMLHttpRequest無法加載https://blockchain.info/tobtc?currency=INR&value=1000&cors=true 對預檢請求的響應未通過訪問控制檢查:請求的資源上不存在“ Access-Control-Allow-Origin”標頭。 因此,不允許訪問源' http://127.0.0.1:8080 '。

如果通過此URL進行瀏覽,您將知道它允許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>
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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM