簡體   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