You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ruby on Rails API添加/status路由返回204状态码方法咨询

实现GET /status返回204状态码的简便方法

方法一:路由直接处理(最简便)

不需要创建控制器或模型,直接在路由定义里返回响应。打开config/routes.rb,添加以下任意一种写法即可:

# 原生Rack风格写法
get '/status', to: proc { [204, {}, []] }

# 更贴合Rails习惯的写法
get '/status', to: ->(_) { head :no_content }

方法二:极简控制器(适合后续扩展)

如果后续可能需要在/status接口里添加更多检查逻辑(比如数据库连接、缓存状态等),可以创建一个无模型的极简控制器:

  1. 创建app/controllers/status_controller.rb:
class StatusController < ApplicationController
  # 如果项目有全局身份验证拦截,需要跳过该接口的验证
  skip_before_action :authenticate_user!, raise: false

  def index
    head :no_content
  end
end
  1. 在config/routes.rb中绑定路由:
get '/status', to: 'status#index'

验证方式

启动本地服务器后,用curl命令测试:

curl -I http://localhost:3000/status

响应头中会显示HTTP/1.1 204 No Content,说明配置生效。

内容的提问来源于stack exchange,提问作者inarrgd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 03:15:32