martyjs / marty

A Javascript library for state management in React applications
http://martyjs.org
MIT License
1.09k stars 76 forks source link

Accept request header for json #161

Closed bigardone closed 9 years ago

bigardone commented 9 years ago

Hi! I'm using Marty in a Rails application and I have noticed that all requests done by my HttpStores are done as "* / *" instead of being "application/json" which is the format that I need. To do so using jquery for example I can set the dataType: 'json' attribute and I was wondering if something similar could be done in Marty.

This is what request format looks like using jquery ajax:

<Mime::Type:0x007f8d74b18240 @synonyms=["text/x-json", "application/jsonrequest"], @symbol=:json, @string="application/json">

And this is using Marty's HttpStore:

<Mime::Type:0x007f8d789191c0 @synonyms=[], @symbol=nil, @string="*/*">

Thanks in advance and thanks also for the awesome work you're doing here :)

jhollingworth commented 9 years ago

could you give me an example of how you're making the http request? If you pass in an object for the body then Marty should automatically add the application/json header.

bigardone commented 9 years ago

This is how I do it:

CollectionsAPI = Marty.createStateSource
  type: 'http'

  findAll: ->
    @get(Routes.collections_path()).then (res)->
      CollectionsSourceActionCreators.receiveItems res.body
jhollingworth commented 9 years ago

ah, I see. yeah dataType: 'json' would be really helpful here. I will add it to v0.9 (hopefully will be out in a week or two). In the meantime you will have do to

CollectionsAPI = Marty.createStateSource
  type: 'http'

  findAll: ->
    request =
       url: Routes.collections_path()
       headers: { 'content-type': 'application/json' }

    @get(request).then (res)->
      CollectionsSourceActionCreators.receiveItems res.body
bigardone commented 9 years ago

Awesome! thank you very much!

jhollingworth commented 9 years ago

dataType is now in the v0.9 branch (#176). Hopefully this will be out soon

Also I realised my previous example was wrong. It should be

CollectionsAPI = Marty.createStateSource
  type: 'http'

  findAll: ->
    request =
       url: Routes.collections_path()
       headers: { 'Accept': 'application/json' }

    @get(request).then (res)->
      CollectionsSourceActionCreators.receiveItems res.body
bigardone commented 9 years ago

With the headers: { 'Accept': 'application/json' } option works like a charm, thanks!