简体   繁体   中英

Why is Angular JS $http.get() not working in this code?

I'm trying to get the RSS feeds from a link. The ng-click function getNews("SomeText") is working, I have confirmed it with filling a container with some text. However, $http.get() is not working. I only want to show the data for now, I'll parse it later.

Here is my Angular JS code.

var app = angular.module("app",[]);
app.controller("newsController", function($scope, $http) {
  $scope.getNews = function(topic) {

    if (topic === "NAmerica") {
    //The program enters this part, I have confirmed, only $http.get() doesn't work
      $http.get('http://www.usnews.com/rss/education')
      .then(function (response) {
        $scope.message = response;

      });
    }
  };
});

My HTML file has this structure:

<html ng-app="app">
   <body ng-controller="newsContainer">
       <a href="#" id="NAmerica" ng-click="getNews('NAmerica')">US &amp; Canada</a>
       <p> {{message}} </p>
   </body>
</html>

As already noted in comments, modern browsers cannot simply request arbitrary URLs via AJAX. This restriction is entirely intentional and called the Same-Origin Policy . By default, browsers can only execute AJAX requests to the same domain that the JavaScript is executed on.

Usually, there are a few options that you can take.

  1. Cross-Domain requests are allowed when the requested site contains a Cross-Origin Resource Sharing (CORS) header in its HTTP response, which usually looks something like this:

     Access-Control-Allow-Origin: http://yoursite.com 

    Of course, this is only an option when you're in control of the domain that you're requesting content from. If you're executing requests to a 3rd party site, there's usually nothing that you can do about this on your own.

    Btw, you should also be able to see a respective error message in your browser console.

  2. Request the foreign content using a server-side script on your domain, for instance using a PHP or [insert random server-side scripting language here] script on your server that you then request via AJAX. That way, you can work around the Same-Origin Policy, since the user's browser can now request a resource on your own domain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM