3
votes

I'm having a hard time getting a good response from the tumblr api on a GULP localhost.

using postman, I get the proper response from the request 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. 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. Origin 'http://localhost' is therefore not allowed access.

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);
  }
}
1
To get around the Access-Control-Allow-Origin issue, you need to use JSONP, which the Tumblr v2 API supports.approxiblue
Thanks for the links, that was very insightfulFelipe

1 Answers

3
votes

This is CORS limitation. 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.

To workaroud the problem you should make use of JSONP approach supported by Tumblr. You would also use HttpClient for jsonp method.

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