【问题标题】:How to get Rails to respond with json based on headers如何让 Rails 根据标头使用 json 响应
【发布时间】:2016-07-07 08:47:45
【问题描述】:

我正在使用 Rails 4 构建一个 API,在我的控制器中我使用 respond_to 来区分 htmljson 请求,这一切都很好。在 Postman 中测试我的 API 时,我添加了以下标头:Content-Type: application/json,但在我的请求中,我仍然需要在其末尾添加 .json,如下所示:https://myapi.com/api/users.json 否则 Rails 将响应 html尽管存在上述标题。

我的问题是:有没有一种方法可以让 Rails 识别 Content-Type: application/json 标头并在没有我使用 url 中的 .json 部分的情况下以 json 响应,如下所示:https://mypai.com/api/users

【问题讨论】:

    标签: ruby-on-rails ruby json ruby-on-rails-4


    【解决方案1】:

    您还需要将Accept 标头设置为Accept: application/json

    如果您对为什么以及这两个标题之间的区别感到好奇,这篇文章的答案最好地解释它:https://webmasters.stackexchange.com/questions/31212/difference-between-the-accept-and-content-type-http-headers

    【讨论】:

    • 那么我应该在哪里设置Accept 标头?
    • 其实,没关系!我得到了它。仅供参考(您可能希望编辑您的答案以供参考)您需要添加另一个标题Accept: application/json
    【解决方案2】:

    如果您在视图中使用任何链接助手,只需添加格式信息,例如posts_path(format: :json)

    【讨论】:

    • 我没有使用视图
    猜你喜欢
    • 2017-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-10
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多