引发异常时如何保留响应标头? [英] How to preserve response headers when raising an exception?

查看:63
本文介绍了引发异常时如何保留响应标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用机架信息在我们的API请求中添加CORS响应标头。

I'm using rack-cors to add the CORS response headers in our API requests.

当请求成功(200)时,它工作正常。但是当应用程序引发异常 ActiveRecord :: RecordNotFound (404)或通过 authenticate_user设计/ /无效的凭据!(401)-它不使用CORS响应标头进行响应。

It works fine when the requests succeeded (200). But when the application raises an exception ActiveRecord::RecordNotFound (404) or devise/invalid credentials through authenticate_user! (401) - it doesn't respond with the CORS response headers.

不仅限于机架式。

最大的问题是在客户端(浏览器),因为它没有显示基于正确的错误的信息,而没有引发异常。状态代码上显示:

The big problem is in the client side (browser), because instead of showing the proper error based on the status code, it shows:


XMLHttpRequest无法加载 http://development.com:4000/orders/1 。所请求的资源上没有 Access-Control-Allow-Origin标头。因此,不允许访问' http://development.com:3000 '。

XMLHttpRequest cannot load http://development.com:4000/orders/1. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://development.com:3000' is therefore not allowed access.

如果我手动捕获到异常 rescue_from render json:{},状态:500 它以标头响应。

If I manually catch the exception rescue_from and render json: {}, status: 500 it responds with the headers.

推荐答案

我一直在与这个问题作斗争,答案是:

I was fighting with that problem for long and the answer is:

设置Rack :: Cors中间件的顺序很重要。像这样使用它:

the order in which you set the Rack::Cors middleware matters. Use it like this:

config.middleware.insert_after Rails::Rack::Logger, Rack::Cors, :logger => Rails.logger do
  allow do
    origins '*'
    resource '*', headers: :any, methods: %i[get post patch put delete options]
  end
end

更多信息: https://github.com/cyu/rack-cors/issues/33

这篇关于引发异常时如何保留响应标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆