weixin_33698043 2014-09-26 20:26 采纳率: 0%
浏览 38

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.

  • 写回答

2条回答 默认 最新

  • 撒拉嘿哟木头 2014-09-26 20:30
    关注

    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).

    评论

报告相同问题?