首页 > 解决方案 > 如何使用 rack-cors 在 Access-Control-Expose-Headers 标头中声明 Content-Range

问题描述

为了从前端访问我的 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-railsrubycorsrack-cors

解决方案


根据原始 repo 中的测试用例key: value,不可能通过 rack-cors 接受的路由定义中的 pair

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

推荐阅读