简体   繁体   English

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

[英]aurelia http-fetch-client no access control for tumblr api

I'm having a hard time getting a good response from the tumblr api on a GULP localhost. 我很难在GULP本地主机上获得tumblr api的良好反应。

using postman, I get the proper response from the request URL: 使用邮递员,我从请求URL得到正确的答复:

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

I can't seem to get the response in my aurelia module though. 我似乎无法在我的aurelia模块中获得响应。 I keep getting the error 我一直在收到错误

Fetch API cannot load http://api.tumblr.com/ ........... No 'Access-Control-Allow-Origin' header is present on the requested resource. Fetch API无法加载http://api.tumblr.com/ ............请求的资源上没有“Access-Control-Allow-Origin”标头。 Origin ' http://localhost ' is therefore not allowed access. 因此不允许Origin'http:// localhost '访问。

Code is below: 代码如下:

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

This is CORS limitation. 这是CORS限制。 You can't make cross-domain requests if your origin is not granted permission. 如果您的来源未获得许可,则无法进行跨域请求。 It works for server-side requests of course, that's why you can fetch data without problem in case of nodejs request. 它当然适用于服务器端请求,这就是为什么在nodejs请求的情况下你可以毫无问题地获取数据。

To workaroud the problem you should make use of JSONP approach supported by Tumblr. 要解决这个问题,你应该使用Tumblr支持的JSONP方法。 You would also use HttpClient for jsonp method. 您还可以将HttpClient用于jsonp方法。

In your case code will be: 在您的情况下代码将是:

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