【问题标题】:Rails: how to set json format for redirect_toRails:如何为 redirect_to 设置 json 格式
【发布时间】:2013-02-24 14:13:00
【问题描述】:

如何不重定向到 html 格式,而是重定向到 json?

我想要这样的东西:

redirect_to user_path(@user), format: :json

但这不起作用,我仍然重定向到html路径。

【问题讨论】:

    标签: ruby-on-rails ruby json redirect routing


    【解决方案1】:

    我又读了一些 apidock... 这很简单。我应该像这样在路径助手中指定格式:

    redirect_to user_path(@user, format: :json)
    

    【讨论】:

    • 如果这是在 format.js 请求中完成的,那么响应实际上不会重定向页面,它只是将 html 异步发送到浏览器。这是唯一的方法吗:stackoverflow.com/questions/18629811/…
    • @ajbraus JS 不是 JSON。您链接的问题/答案正在处理指定格式实际上是将执行的 javascript 的请求,而不是针对您响应 API 请求的情况(甚至可能来自支持 JavaScript 的客户端,例如 iOS 应用程序) .
    【解决方案2】:

    接受的答案(在 redirect_to 选项中指定 format: :json)在 Rails 5.2 API 应用程序中对我不起作用;带有Accept: application/json 标头的请求。

    使用redirect_to "/foo", format: :json 会得到这样的响应(为简洁起见进行了编辑):

    HTTP/1.1 302 Found
    Content-Type: text/html; charset=utf-8
    Location: /foo
    
    <html><body>You are being <a href="/foo">redirected</a>.</body></html>
    

    这不适用于 API,因此我完全没有使用 redirect_to,而是改用 head:

    head :found, location: "/foo"
    

    这会导致以下响应(再次,为简洁起见)而没有正文,这正是我想要的:

    HTTP/1.1 302 Found
    Content-Type: application/json
    Location: /foo
    

    在我的情况下,我没有重定向到我的 Rails 应用程序中的页面,所以我没有使用 URL 帮助程序,但如果你这样做(例如 user_path 或 redirect_to @user),你可以提供相关的您的 URL 助手的选项,如下所示:

    head :found, location: user_path(user, format: :json)
    # or
    head :found, location: url_for(@user, format: :json)
    

    【讨论】:

    • 如果您指定 302 或除 304 之外的任何其他 3xx,用户代理可能会自动重定向到给定的 Location 标头。在我的例子中,我从 API 发送带有 Location 标头的 304,通过在前端检查这些数据将用户重定向到不同的页面。
    猜你喜欢
    • 2013-09-02
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多