1

This is my code:

var url = "http://www.google.com/finance?q=MSFT" 
$http.get(url).success(function (data, status, headers, config) {
    alert('successful');
}).error(function (data, status, headers, config) {
    alert('failed');
});

This is working fine. However, if I change the url to Yahoo or Reuters as follows, it always returns 404 error.

url = "http://finance.yahoo.com/q/pr?s=MSFT";
url = "http://www.reuters.com/finance/stocks/companyProfile?rpc=66&symbol=MSFT"

Those are all valid URLs when you enter into Chrome.

I understand there are related questions about $http.get at stackoverflow, but I tried some suggestions and still can't make it work. I'm very curious why the same request works for Google, but not for Yahoo and Reuters?

UPDATE 1: As some suggested it may be a CROSS-ORIGIN problem, so I added the following code from here to my project:

app.config(['$httpProvider', function ($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

However, it doesn't help.

I looked at Network traffic log in Chrome, the request status is (canceled). Any clue why?

UPDATE 2: Actually, I overlooked the error message in Chrome console. it shows:

XMLHttpRequest cannot load http://finance.yahoo.com/q?s=MSFT. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1486' is therefore not allowed access.

So, it does seem to be a Cross-Origin issue. However, the UPDATE 1 code doesn't seem to have any effect on this. What did I do wrong? Also, why it didn't complain about Google?

scniro
  • 16,844
  • 8
  • 62
  • 106
newman
  • 6,841
  • 21
  • 79
  • 126
  • Do you have perhaps an `Access-Control-Allow-Origin` error? – domokun Jul 07 '14 at 15:18
  • data in error callback is empty string. – newman Jul 07 '14 at 16:25
  • As I told you, this is exactly an `Access-Control-Allow-Origin`. This is because both websites doesn't allow Cross-Origin requests. You can bypass this running Chrome with `--disable-web-security` flag. Firefox should work as is though. – domokun Jul 07 '14 at 17:32
  • Okay, I got it now. Thanks. However, I still don't understand why this isn't a problem for accessing Google site? – newman Jul 07 '14 at 19:08
  • Because they *probably* set something like ` header('Access-Control-Allow-Origin: *');` which allows any origin. – domokun Jul 08 '14 at 07:02

1 Answers1

1

This sounds like a cross-origin request issue.

Someone with a similar problem found a way to do cross-origin requests with angular here: AngularJS 1.2 cross origin requests are only supported for HTTP

and probably a more relevant topic here: $http.get is not allowed by Access-Control-Allow-Origin but $.ajax is

Community
  • 1
  • 1
MarkW
  • 75
  • 1
  • 10