JSONP意外语法错误(API不支持JSONP)

时间:2018-06-15 19:38:52

标签: angularjs jsonp

我的功能:

function getMarketData_() {
      $http({
        method: 'JSONP',
        url: 'https://api.coinmarketcap.com/v2/ticker/',
      }).then(function(response) {
        console.log('ran');
      }).catch(function(response) {
        console.log('Error');
      });
    }

错误:

Uncaught SyntaxError: Unexpected token :

返回的JSON中的错误位置:

enter image description here

1 个答案:

答案 0 :(得分:0)

API不支持JSONP。

测试点击:https://api.coinmarketcap.com/v2/ticker/?callback=test

支持JSONP的API会发回类似的内容:

test({
    "data": {
        "1": {
            "id": 1, 
            "name": "Bitcoin", 
            "symbol": "BTC", 
            "website_slug": "bitcoin", 
            "rank": 1, 
            "circulating_supply": 17095362.0, 
            "total_supply": 17095362.0, 
            "max_supply": 21000000.0, 
            "quotes": {
                "USD": {
                    "price": 6530.3, 
                    "volume_24h": 4015800000.0, 
                    "market_cap": 111637842469.0, 
                    "percent_change_1h": -0.66, 
                    "percent_change_24h": -2.31, 
                    "percent_change_7d": -14.6
                }
            }, 
            "last_updated": 1529097276
        }
    }
})

有关详细信息,请参阅Wikipedia - JSONP

另见Angular 1.6.3 is not allowing a JSONP request that was allowed in 1.5.8

API支持CORS。

测试用途:

https://www.test-cors.org/#?client_method=GET&client_credentials=false&server_url=https%3A%2F%2Fapi.coinmarketcap.com%2Fv2%2Fticker%2F&server_enable=true&server_status=200&server_credentials=false&server_tabs=remote

当用户尝试使用$http.get并获取:

时,通常会出现此问题
  

XMLHttpRequest无法加载https://www.[website].com/请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:4300”访问。

然后有人建议$http.jsonp作为解决方法。这仅在API支持JSONP时有效。

有关详细信息,请参阅

相关问题