Search code examples
javascriptjsonjsonpaurelia

Error during reading json in Aurelia.io example


I'm extending aurelia's get started app by adding custom moduls. I've got an error "Uncaught SyntaxError: Unexpected token :" while reading a json. But json validator doesn't find any errors.

Here is my json { "news": [ { "title": "Lorem Ipsum is simply dummy text", "type": "news", "tags": [ "news", "fish", "loremipsumdolor" ], "text": "Lorem Ipsum is simply dummy text of the printing and typesetting industry." }, { "title": "Lorem Ipsum", "type": "news", "tags": [ "news", "fish" ], "text": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s." } ] }

And here is my module that tries to load that json (basically it's a copy-paste from flickr.js which can be found in example code) ` import {inject} from 'aurelia-framework'; import {HttpClient} from 'aurelia-http-client';

@inject(HttpClient)
export class News{
  heading = 'News';
  items = [];
  url = '/res/data.json';

  constructor(http){
    this.http = http;
  }

  activate(){
    debugger;
    return this.http.jsonp(this.url).then(response => {
      this.items = response.content.news;
    });
  }

  canDeactivate(){
    return confirm('Are you sure you want to leave?');
  }
}

' When example code is executed it loads json from flikr and wraps it in jsonp_callback_92661(). That's the only difference. May it be the root of my problem?


Solution

  • Yes, that's the root of your problem. You are using jsonp when you don't really need it. Since you are serving a static json file yourself, and presumably served over the same domain the main app lives, you don't need to use jsonp. Good explanations about jsonp are here in SO if you are not already familiar (flicker wraps the response in a function call because that's needed for jsonp to work).

    You should be able to use get:

    return this.http.get(this.url).then(response => {
      //not sure if response.content is an object already.
      //you may need to JSON.parse response.content
      this.items = response.content.news;
    });