为了账号安全,请及时绑定邮箱和手机立即绑定

FileServer 使用 MIME 类型错误而不是 404 处理 not found css

FileServer 使用 MIME 类型错误而不是 404 处理 not found css

Go
繁花如伊 2022-06-13 16:17:58
我正在运行一个基本http.FileServer的静态站点服务,我遇到了一个问题,即对不存在的 css 文件的请求因 MIME 类型错误而被取消:Refused to apply style from 'http://localhost:8080/assets/main.css' because its MIME type ('text/plain')理想情况下,我更希望用 404 错误来处理它,因为它实际上应该是这样的。我可以尝试任何可能的解决方法吗?
查看完整描述

1 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

从net/http源代码(fs.go):


// toHTTPError returns a non-specific HTTP error message and status code

// for a given non-nil error value. It's important that toHTTPError does not

// actually return err.Error(), since msg and httpStatus are returned to users,

// and historically Go's ServeContent always returned just "404 Not Found" for

// all errors. We don't want to start leaking information in error messages.

func toHTTPError(err error) (msg string, httpStatus int) {

    if os.IsNotExist(err) {

        return "404 page not found", StatusNotFound

    }

    if os.IsPermission(err) {

        return "403 Forbidden", StatusForbidden

    }

    // Default:

    return "500 Internal Server Error", StatusInternalServerError

}

文件服务器返回 200 和 404 错误的纯文本文件。浏览器尝试将此纯文本错误页面解释为 CSS 文件,并引发错误。


这种返回纯文本文件的行为不能被FileServer().


正如已经指出的那样,这并不是net/http.


如果由于某种原因您不希望这种行为,您可以探索为 404 响应创建自定义处理程序,这已在此线程中进行了探索。您还可以使用像 Gorilla 这样的路由库,它对未找到的页面具有可覆盖的行为。


查看完整回答
反对 回复 2022-06-13
  • 1 回答
  • 0 关注
  • 177 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号