【问题标题】:How do I declare Content-Range in the Access-Control-Expose-Headers header using rack-cors如何使用 rack-cors 在 Access-Control-Expose-Headers 标头中声明 Content-Range
【发布时间】:2020-11-07 18:26:59
【问题描述】:

为了从前端访问我的 api,它要求我在 Access-Control-Expose-Headers 标头中声明 Content-Range。我不知道具体怎么写。

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
      headers: ["Access-Control-Expose-Headers", "Content-Range: 0-24/319"], 
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*',
      headers: :any, 
      expose: ["Content-Range: orders 0-24/319"],
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

知道我写错了什么吗?

【问题讨论】:

    标签: ruby-on-rails ruby cors rack-cors


    【解决方案1】:

    根据原始仓库中的test case 不可能在路由定义中传递 key: value 对 rack-cors 会接受的

    Rails.application.config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*',
          headers: :any, 
          expose: ["Content-Range"],
          methods: [:get, :post, :put, :patch, :delete, :options, :head]
      end
    end
    

    然后例如,您可以在BaseController 中写入默认值,然后从中继承每个控制器

    class BaseController < ApplicationController
      after_action :apply_content_range_header
    
      protected
      def apply_content_range_header
        response.headers['Content-Range'] = 'orders 0-24/319'
      end
    end
    

    然后在你的控制器中调用它

    class ProductsController < BaseController
      def index; end # your products#index will have Content-Range header
    end
    

    【讨论】:

    • 非常感谢您。将尝试!
    • 通常你应该从ApplicationController继承BaseController,所有你其他的控制器比如ProductsControllerBaseController继承,我会更新答案
    • 谢谢。完美运行。我真的很感激!
    猜你喜欢
    • 2016-05-18
    • 2013-06-12
    • 2019-05-18
    • 1970-01-01
    • 2017-03-24
    • 2015-12-29
    • 2016-05-18
    • 2015-11-26
    • 1970-01-01
    相关资源
    最近更新 更多