机架应用程序提供设置了 Content-Type 的 js 文件,但浏览器显示 Mimetype 为“”

问题描述 投票:0回答:1

我有一个机架应用程序:

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 类型进行响应?

ruby mime-types rack
1个回答
0
投票

我能够通过使用实际的 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
  }
© www.soinside.com 2019 - 2024. All rights reserved.