为什么Node.js无法提供.woff文件

jiy*_*ong 7 http nginx node.js

.woff出于某些网络原因在中国从Google网络字体下载了该文件.以前我@font-faceGithub Pages上尝试过,它可以工作.但是这次花了我一个小时的时间来找到被打破的地方.

我使用Node来提供静态文件mime,content-type看起来是application/x-font-woff和我在CoffeeScript中的代码:

exports.read = (url, res) ->
  filepath = path.join __dirname, '../', url
  if fs.existsSync filepath
    file_content = fs.readFileSync filepath, 'utf8'
    show (mime.lookup url)
    res.writeHead 200, 'content-type': (mime.lookup url)
    res.end file_content
  else
    res.writeHead 404
    res.end()
Run Code Online (Sandbox Code Playgroud)

由于content-type.woffGithub上的页面时application/octet-stream,我只是出来的CommNet该行在我的代码,使之同.但它还是失败:

exports.read = (url, res) ->
  filepath = path.join __dirname, '../', url
  if fs.existsSync filepath
    file_content = fs.readFileSync filepath, 'utf8'
    show (mime.lookup url)
    # res.writeHead 200, 'content-type': (mime.lookup url)
    res.end file_content
  else
    res.writeHead 404
    res.end()
Run Code Online (Sandbox Code Playgroud)

最后,我切换到Nginx服务器来提供.woff文件..最后它开始工作.

但是如何在Node上修复它呢?

psy*_*opz 5

在此行中,fs.readFileSync(filepath, 'utf8')编码设置为'utf8'。它需要是'binary'

此外,该res.end(file_content)函数需要传递正确的编码。尝试res.end(file_content, 'binary')

我遇到了同样的问题,必须自己解决,这个答案似乎在网上任何地方都不存在。