jasonswett / angular-for-rails-developers-issues

Issues found in Angular for Rails Developers book
https://www.angularonrails.com/angular-rails-developers/
5 stars 1 forks source link

Page 31: Serving JSON up to Firefox #6

Open neeklamy opened 8 years ago

neeklamy commented 8 years ago

The Problem

Firefox has a problem with correctly receiving the JSON formatted data, the issue is caused by the request headers that it sends along. The default:
Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"

Google Chrome by contrast sends this request header, which accepts anything:

Accept: */*

So, if you’re using Firefox, when you get to this point in the book, where the list of books is expected, nothing appears. Nothing appears because ng server has sent back the main index.html instead of the desired JSON in response, viewing Firefox’s developer tools console shows this error:

EXCEPTION: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

(The first and unexpected character is the first character <.)

The Fix

One way to fix this is to change the Header sent with the http.get.

Before:

// src/app/book-list/book-list.component.ts
[…]
import { Http } from '@angular/http';
[…]

  ngOnInit() {
    this.http.get('/api/books.json')
      .subscribe((response) => this.books = response.json());
  }

[…]

After:

// src/app/book-list/book-list.component.ts
[…]
import { Http, Headers } from '@angular/http';
[…]

  ngOnInit() {
    this.http.get('/api/books.json', { headers: new Headers({'Accept' : '*/*' }) })
      .subscribe((response) => this.books = response.json());
  }

[…]

Maybe there’s a better way? Maybe this will be fixed in Angular? Source: angular/angular-cli#889

jasonswett commented 8 years ago

Hey @neeklamy, I just want to acknowledge that I'm seeing these issues you've submitted as say thanks for the help. I'll be going through and addressing all these soon.