【发布时间】:2013-02-24 14:13:00
【问题描述】:
如何不重定向到 html 格式,而是重定向到 json?
我想要这样的东西:
redirect_to user_path(@user), format: :json
但这不起作用,我仍然重定向到html路径。
【问题讨论】:
标签: ruby-on-rails ruby json redirect routing
如何不重定向到 html 格式,而是重定向到 json?
我想要这样的东西:
redirect_to user_path(@user), format: :json
但这不起作用,我仍然重定向到html路径。
【问题讨论】:
标签: ruby-on-rails ruby json redirect routing
我又读了一些 apidock... 这很简单。我应该像这样在路径助手中指定格式:
redirect_to user_path(@user, format: :json)
【讨论】:
接受的答案(在 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)
【讨论】: