从http客户端检索json出错

Error retrieving jsonp from aurelia http client

本文关键字:json 出错 检索 客户端 http      更新时间:2023-09-26

我有一个应用程序,我正在使用Aurelia创建。我希望通过ajax从instagram的用户检索最新的图像。我尝试使用Aurelia http客户端,因为这就是Aurelia入门页面上的Flickr示例所使用的。

如果我使用http.get,那么我从instagram得到一个CORS错误。尝试http.jsonp,检查的响应显示了正确的格式,但在执行处理响应的回调之前,我得到了一个解析错误(意外令牌":")。

am能够使用jQuery通过AJAX成功检索图像,但我很好奇知道我在Aurelia http客户端做错了什么。

以下是视图模型的相关部分:

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';
@inject(HttpClient)
export class Welcome {
  images = [];
  url = '[INSTAGRAM_URL]';
  constructor(http){
    this.http = http;
  }
  activate(){
    return this.http.jsonp(this.url).then(response => {
      this.images = response.data.map(function (d) {
            return {
                src: d.images.standard_resolution.url,
                caption: d.caption.text,
                when: d.created_time
            };
        });
    });
  }
}

Instagram API期望callback GET参数出现在请求URL中。这个参数应该是一个函数名,以便将响应对象包装到其中(Aurelia将添加类似&callback=jsonp_callback_59563的东西)。它与jQuery一起工作的原因。jsonp的缺点是它在后台自动添加callback参数。

正确的代码应该是:
return this.http.jsonp(this.url, 'callback').then(response => {
  this.images = response.content.data.map(function (d) {
        return {
            src: d.images.standard_resolution.url,
            caption: d.caption.text,
            when: d.created_time
        };
    });
});