我正在使用 Rails 4 构建 API,在我的 Controller 中我使用 respond_to
来区分 html
和 json
请求一切正常。在 Postman 中测试我的 API 时,我添加了以下 header :Content-Type: application/json
但在我的请求中我仍然需要在末尾添加 .json
它像这样:https://myapi.com/api/users.json
否则 Rails 将以 html
响应,即使上述 header 存在。
我的问题是:有没有一种方法可以让 Rails 识别 Content-Type: application/json
header 并用 json
响应,而无需我使用 .json
部分在 url 中,如下所示:https://mypai.com/api/users
?
最佳答案
您还需要将 Accept
header 设置为 Accept: application/json
如果您对原因以及这两个 header 之间的区别感到好奇,这篇文章的答案最能说明问题:https://webmasters.stackexchange.com/questions/31212/difference-between-the-accept-and-content-type-http-headers
关于ruby-on-rails - 如何让 Rails 响应基于 header 的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38241126/