我有一个Rails 5 API项目,我使用rack-cors
。
场合:
我在public/files
文件夹中有一些静态JSON文件,如下所示:
{
"example": "123456"
...
}
我可以在开发中完美地访问它们(来自Angular客户端),但它不能在生产中使用。
在制作中,我收到了常见错误:
XMLHttpRequest无法加载 https://myhost.com/files/my_file.json。没有 '访问控制允许来源'标题出现在请求的上 资源。
最奇怪的是我可以在浏览器中手动访问网址(https://myhost.com/files/my_file.json
)而不会出现任何问题。
实际配置:
配置/初始化/ cors.rb:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins my_origins
resource '*',
expose: ['awesome_token'],
headers: :any,
methods: %i[delete get head options patch post put]
end
end
可能的配置:
经过一些研究,我发现了以下内容:
环境/ production.rb :
# Added the following
config.public_file_server.enabled = true
cors.rb :
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins my_origins
resource '*',
expose: ['awesome_token'],
headers: :any,
methods: %i[delete get head options patch post put]
end
end
# Added the following
Rails.application.config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: %i[delete get head options patch post put]
end
end
但它完全没有区别。
所以,我的问题是:我有什么东西不见了吗?怎么了?
PS:每个请求都运行正常,问题出在public/files
文件夹中的静态JSON文件(生产构建中)。