【问题标题】:aurelia http-fetch-client no access control for tumblr apiaurelia http-fetch-client 没有 tumblr api 的访问控制
【发布时间】:2015-08-26 16:43:22
【问题描述】:

我很难从 GULP 本地主机上的 tumblr api 获得良好的响应。

使用邮递员,我从请求 URL 得到正确的响应:

http://api.tumblr.com/v2/blog/{any_blog}/posts?limit=5&api_key={key}

不过,我似乎无法在我的 aurelia 模块中得到响应。我不断收到错误

Fetch API 无法加载http://api.tumblr.com/............ 请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost' 因此不允许访问。

代码如下:

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';

@inject(HttpClient)
export class Users{
  heading = 'Blog Posts';
  posts = [];

  constructor(http){
    http.configure(config => {
      config
        .withBaseUrl('http://api.tumblr.com/v2/')
        .withDefaults({
          headers: {
            'Access-Control-Allow-Origin': '*'
          }
        });
    });

    this.http = http;
  }

  activate(){
    return this.http.fetch('blog/{blog_name}.tumblr.com/posts', { limit: 5, api_key: {api_key} })
      .then(response => response.json())
      .then(posts => this.posts = posts);
  }
}

【问题讨论】:

标签: javascript ecmascript-6 aurelia


【解决方案1】:

这是CORS 限制。如果您的来源未获得许可,您将无法发出跨域请求。它当然适用于服务器端请求,这就是为什么您可以在 nodejs 请求的情况下毫无问题地获取数据。

要解决此问题,您应该使用 Tumblr 支持的 JSONP 方法。您还可以将HttpClient 用于jsonp 方法。

在您的情况下,代码将是:

import {inject} from 'aurelia-framework';
import {HttpClient} from 'aurelia-http-client';

@inject(HttpClient)
export class Users{
  heading = 'Blog Posts';
  posts = [];

  constructor(http){
    http.configure(config => {
      config
        .withBaseUrl('http://api.tumblr.com/v2/')
        .withParams({
          limit: 5,
          api_key: '{api_key}'
        });
    });

    this.http = http;
  }

  activate(){
    return this.http.jsonp('blog/{blog_name}.tumblr.com/posts', 'jsonp')
      .then(httpResponse => this.posts = httpResponse.response.response.posts);
  }
}

【讨论】:

  • 我唯一注意到的是您将其更改为当前正在使用的 http-client。我知道这个客户端打算被 http-fetch-client 取代 >> github.com/aurelia/fetch-client
  • Fetch 目前没有 jsonp 方法。所以你应该为此使用 httpclient,至少现在是这样。
猜你喜欢
  • 2017-11-27
  • 2016-03-12
  • 2017-05-11
  • 2014-07-14
  • 2017-12-17
  • 2016-10-22
  • 1970-01-01
  • 2020-03-15
  • 1970-01-01
相关资源
最近更新 更多