ruby 机架应用程序服务的js文件与内容类型设置,但浏览器说Mimetype是“”

zi8p0yeb  于 12个月前  发布在  Ruby
关注(0)|答案(1)|浏览(62)

我有一个rack app:

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.

为什么浏览器声称服务器响应的MIME类型是“”,而curl显示服务器响应的是“application/JavaScript”?

nzrxty8p

nzrxty8p1#

我能够通过使用实际的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
  }

相关问题