Rails:发送401错误而不渲染页面

3
我正在尝试从Rails控制器为Webhooks发送401未授权,但由于我没有渲染页面,似乎无法找到正确的方法。
render plain: "Unauthorized", status: :unauthorized

抛出这个错误:

Read error: #<NoMethodError: undefined method `bytesize' for [:error, "Unauthorized"]:Array>

我不明白为什么会这样,因为

render plain: "Unauthorized", status: 400 

运作良好。

2个回答

3
head(:unauthorized)

返回一个没有内容的响应(只有状态码和头部信息)。

参见ActionController::Head


我也尝试过,但是我仍然得到相同的错误Read error: #<NoMethodError: undefined method 'bytesize' for [:error, "Unauthorized"]:Array> 是否还需要其他内容来使未经授权的响应成功? - spillthebeans
这更像是在消耗响应的另一侧出现了错误,而且没有那段代码就无法回答。 - max
另一方面,我只是用Postman来测试它。 - spillthebeans
奇怪,你有什么中间件可以解释一下吗? - max

1

你是否在使用来自rails_warden或等效中间件的此片段

如果是这样,正确的部分应该是:

  manager.failure_app = Proc.new { |_env|
    ['401', {'Content-Type' => 'application/json'}, [{ error: 'Unauthorized' }.to_json]]
  }

如果有人想要在控制器中传递你发送的响应:['401', {'Content-Type' => 'application/json'}, [_env['action_controller.instance'].response.body]] - idrozd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接