我有一个机架应用程序:
class Responder
def self.call(env)
path = env['PATH_INFO']
path = File.extname(path).blank? ? 'index.html' : path
extension = File.extname(path)
headers = {
'Content-Type' => Rack::Mime.mime_type(extension)
}
[200, headers, [ File.read(File.join(APP_ROOT, path)) ] ]
end
end
这样做的目标是任何像
/foo
或 /bar
这样的路由都会以 index.html
响应,否则任何对 .js
或 .css
请求的文件的请求都将被传递...
测试时,我看到正在设置的标题中的内容类型正确。我什至可以使用curl看到这一点:
curl -i http://localhost:3000/foo
HTTP/1.1 200 OK
Content-Type: text/html
和
curl -i http://localhost:3000/main.js
HTTP/1.1 200 OK
Content-Type: application/javascript
然而,当我尝试在浏览器中查看应用程序时,任何调用 javascript 文件的脚本标记都会失败,并显示以下错误:
main.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.
当curl 显示服务器正在使用“application/javascript”进行响应时,为什么浏览器声称服务器正在使用“” MIME 类型进行响应?
我能够通过使用实际的 Rack::Request / Rack::Response 对象来使 mime 类型的东西正常工作。
get '(*path)', to: ->(env) {
request = Rack::Request.new(env)
response = Rack::Response.new
extension = File.extname(request.path_info)
if extension.blank?
content_type = Rack::Mime.mime_type('.html')
filename = 'index.html'
else
content_type = Rack::Mime.mime_type(extension)
filename = request.path_info
end
response.header['Content-Type'] = content_type
response.status = 200
response.write File.read("public/app/#{filename}")
response.finish
}