I read your Updating your Angular 2 app from rc4 to rc5 post and have been looking at your PeopleService class in your consuming real data with http repo in github.
Hi Charles! ^_^
That’s to account for how different browsers behave and because it’s the right thing to do since we expect the response to be json.
If I omit the Accept: application/json header in Chrome, Chrome will include the Accept header with a value of */* and the API will return it’s preferred media type which in this case is application/json. (It’s up to the API implementer to make that decision when they’re implementing their API). So, in this case, even if I don’t add a header explicitly everything works as fine.
If I omit the Accept header in Firefox, Firefox will include the Accept header with a value of text/html. The star wars API is configured to respond with help web pages for any given resource when the media type is text/html. That you can have different representations for the same resource is a pretty core principle of RESTful APIs, so it’s actually a pretty neat API in that sense. For the case of our application though this means that, all of the sudden, we’re getting an html response that we try to parse as if it were JSON and it crashes our app.
So that’s why we have the getHeaders
in the example, and explicitly setting the Accept
header to application/json
. When you are consuming a REST API you need to specify with media types you can consume so that the API provider can either give you the right representation or an error message that you can properly handle when the representation is not available (this is known as *Content Negotiation
). In absence of that each browser is going to use it’s own defaults and each API implementer is going to respond based on how the implementers thought best.
Hope it helped, ^_^
Have a nice day!
* Content negotiation
(from Wikipedia) are mechanisms defined as a part of HTTP
that make it possible to serve different versions of a document (or more generally, representations of a resource) at the same URI
, so that user agents
can specify which version fit their capabilities the best. One classical use of this mechanism is to serve an image in GIF
format, so that a browser that cannot display PNG images (e.g. MS Internet Explorer 4) will be served the GIF version.
HTTP provides for several different content negotiation mechanisms including: server-driven (or proactive), agent-driven (or reactive), transparent, and/or hybrid combinations thereof.