aurelia http-fetch-client 没有对 tumblr 的访问控制 api

aurelia http-fetch-client no access control for tumblr api

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

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

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

虽然我似乎无法在我的 aurelia 模块中得到响应。我一直收到错误

Fetch API cannot load http://api.tumblr.com/........... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

代码如下:

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);
  }
}

这是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);
  }
}