如何让Rails根据标头使用json进行响应 [英] How to get Rails to respond with json based on headers
问题描述
我正在使用Rails 4构建API,并且在我的控制器中使用respond_to
来区分html
和json
请求,它们都可以正常工作.在Postman中测试我的API时,我添加了以下标头:Content-Type: application/json
,但在我的请求中,我仍然需要在其末尾添加.json
,如下所示:https://myapi.com/api/users.json
否则,Rails甚至会以html
响应尽管存在上述标头.
I'm building an API with Rails 4 and in my controller I'm using respond_to
to differentiate between html
and json
request which all works fine. While testing my API in Postman, I've added the following header: Content-Type: application/json
but in my request I still need to add .json
at the end of it like so: https://myapi.com/api/users.json
otherwise Rails will respond with html
even though the aforementioned header is present.
我的问题是这样:Rails是否可以识别Content-Type: application/json
标头并用json
响应,而无需我像下面这样使用url中的.json
部分:https://mypai.com/api/users
?
My question is this: is there a way that Rails can recognise the Content-Type: application/json
header and respond with json
without me using the .json
part in the url like so: https://mypai.com/api/users
?
推荐答案
您还需要将Accept
标头设置为Accept: application/json
You also need to set the Accept
header to Accept: application/json
如果您对原因以及两个标头之间的区别感到好奇,则此帖子的答案将为您提供最好的解释:
If you're curious as to why, and the difference between the two headers, the answers to this post explain it best: https://webmasters.stackexchange.com/questions/31212/difference-between-the-accept-and-content-type-http-headers
这篇关于如何让Rails根据标头使用json进行响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!