CORS无法在Angular中工作?

I am trying to GET information from this site https://bitcoinindex.es/api/v0.1/coinbase/usd/btc/last

Using the $http service

After looking all over the internet Here is my code in coffeescript

angular.module('blackmoonApp')
  .controller 'PricingCtrl', ($scope, $http) ->
    $http.defaults.useXDomain = true
    $http.get("https://bitcoinindex.es/api/v0.1/coinbase/usd/btc/last",
      headers:
        "Access-Control-Allow-Origin": "*"
    ).success (JSON) ->
      console.log JSON

The Result is

"XMLHttpRequest cannot load https://www.bitstamp.net/api/ticker/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access."

I am not sure if the website is blocking me (which wouldn't make sense because it is an API) or if AngularJS isn't able to work with CORS.

Access-Control-Allow-Origin is a response header.

This:

  headers:
    "Access-Control-Allow-Origin": "*"

… sets a request header.

You need to set it on https://www.bitstamp.net/api/ticker/, not in your JavaScript.

It would defeat the object if any JavaScript could grant itself permission to access any server.


I am not sure if the website is blocking me (which wouldn't make sense because it is an API)

Blocking is the default behaviour. Explicit permission must be granted to allow JavaScript from other origins access. Otherwise anyone with a bitstamp account could have their bitcoins stolen by visiting a website that used the API (since it would be their browser, with their cookies, making the request).

From your code:

$http.get("https://www.bitstamp.net/api/ticker/",
  headers:
    "Access-Control-Allow-Origin": "*"
)

We see that you are attempting to send the Access-Control-Allow-Origin header in the GET request.

CORS doesn't work that way; the Access-Control-Allow-Origin header must be present in the response sent by the server (and, of course, such header must include the exact same domain of the page that sent the request).

From my tests (unlikely, but your results may differ):

  • https://bitcoinindex.es/api/v0.1/coinbase/usd/btc/last only allows CORS requests from its own domain (the response had Access-Control-Allow-Origin:https://bitcoinindex.es) which is kind of pointless; and
  • https://www.bitstamp.net/api/ticker/ didn't have the Access-Control-Allow-Origin header at all.