繁体   English   中英

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无法加载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);
  }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM