我有像下面这样的AngularJS代码,但遗憾的是它无法正常工作,我看到 XMLHttpRequest无法加载 lipsum/ 。在JS控制台中,请求的资源上没有Access-Control-Allow-Origin标题。
I have the piece of AngularJS code like below, but unfortunately it doesn't work correctly and I see "XMLHttpRequest cannot load lipsum/. No 'Access-Control-Allow-Origin' header is present on the requested resource" in JS console.
var app = angular.module('plunker', []); app.config(function($sceDelegateProvider) { $sceDelegateProvider.resourceUrlWhitelist([ 'self', 'lipsum/**' ]); }) .controller('MainCtrl', function($scope, $sce, $http) { var url = 'lipsum/'; $http({ url: $sce.trustAsResourceUrl(url), method: "GET" }).then( function(response) { console.log('success', response); $scope.status = response.status; }, function(response) { console.log('error', response); $scope.status = response.status; } ); });plnkr.co/edit/ZDNJ3bfO1YlRQhUmNHZj?p=preview
如何使其正常工作并获得成功使用$ http方法回复?
How to make it working correctly and getting successful response by using $http methods?
感谢您的帮助!
推荐答案假设 lipsum/ 是您实际想要获取的网站,您可以这样做:
Assuming lipsum/ is the site you actually want to fetch, you can do this:
var url = "cors-anywhere.herokuapp/lipsum/";...并且您的前端代码将按预期工作。
…and your frontend code will work as expected.
可行的原因是,它导致请求转到 cors-anywhere.herokuapp ,一个开放/公共CORS代理,它将然后将请求发送到 lipsum/ 。
The reason that works is, it causes the request to go to cors-anywhere.herokuapp, a open/public CORS proxy which will then send the request on to lipsum/.
当该代理获得响应时,它将接受它并向其添加 Access-Control-Allow-Origin 响应头,然后将其作为响应传递回您的请求前端代码。
And when that proxy gets the response, it’ll take it and add the Access-Control-Allow-Origin response header to it and then pass that back to your requesting frontend code as the response.
使用 Access-Control-Allow-Origin 响应头的响应是浏览器看到的,因此浏览器出现错误消息现在显示你离开了,浏览器允许您的前端JavaScript代码访问响应。
That response with the Access-Control-Allow-Origin response header is what the browser sees, so the error message the browser is showing you now goes away, and the browser allows your frontend JavaScript code to access the response.
或者使用 github/Rob--W/cors-anywhere/ 等设置您自己的代理。
Or use the code from github/Rob--W/cors-anywhere/ or such to set up your own proxy.
您需要代理的原因是, lipsum/ 本身不会发送 Access-Control-Allow- Origin 响应标头,因此您的浏览器将拒绝让您的前端JavaScript代码访问 lipsum/ 来源的响应。
The reason you need a proxy is, lipsum/ itself doesn’t send the Access-Control-Allow-Origin response header, so your browser will refuse to let your frontend JavaScript code access a response from lipsum/ cross-origin.
developer.mozilla/en-US/docs/Web/HTTP/Access_control_CORS 了解更多详情。
更多推荐
如何将$ sce.trustAsResourceUrl与$ http服务一起使用
发布评论