简体   繁体   中英

Rails HTML Request Render JSON

In my controller, I'm supporting HTML and JSON in my index method by doing:

respond_to do |format|
  format.html
  format.json { render json: @user }
end

When pulling it up in the browser, it renders in HTML naturally. However, when I do a curl call with content-type being application/json to the /user resource (since it's the index method), I still get the HTML as a response.

How can I get the JSON as a response? What else do I need to specify?

You should append .json to the requested url, provided format is defined in the path in routes.rb . This is default when using resources . For example, rake routes should give you something like:

show_user GET    /users/:id(.:format) users#show

To get user in HTML

curl  http://localhost:3000/users/1  

To get user in JSON:

curl http://localhost:3000/users/1.json    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM