FileServer handles not found css MIME 类型错误而不是 404
FileServer handles not found css with MIME type error instead of 404
我是 运行 一个基本的 http.FileServer
静态站点服务人员,我遇到了一个问题,即对 css 不存在的文件的请求被取消MIME 类型错误:
Refused to apply style from 'http://localhost:8080/assets/main.css' because its MIME type ('text/plain')
理想情况下,我更希望用 404 错误来处理它,因为它实际上应该是这样。我可以尝试任何可能的解决方法吗?
来自 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
}
文件服务器 returns 一个 200 的纯文本文件,用于 404 错误。浏览器尝试将此纯文本错误页面解释为 CSS 文件,并抛出错误。
无法在 FileServer()
返回的处理程序上覆盖这种返回纯文本文件的行为。
正如已经指出的那样,这并不是 net/http
中的真正错误。
如果出于某种原因您不希望这种行为,您可以探索为 404 响应创建自定义处理程序,this thread. You could also use a routing library like Gorilla which has overridable behavior 中针对未找到的页面对此进行了探索。
我是 运行 一个基本的 http.FileServer
静态站点服务人员,我遇到了一个问题,即对 css 不存在的文件的请求被取消MIME 类型错误:
Refused to apply style from 'http://localhost:8080/assets/main.css' because its MIME type ('text/plain')
理想情况下,我更希望用 404 错误来处理它,因为它实际上应该是这样。我可以尝试任何可能的解决方法吗?
来自 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
}
文件服务器 returns 一个 200 的纯文本文件,用于 404 错误。浏览器尝试将此纯文本错误页面解释为 CSS 文件,并抛出错误。
无法在 FileServer()
返回的处理程序上覆盖这种返回纯文本文件的行为。
正如已经指出的那样,这并不是 net/http
中的真正错误。
如果出于某种原因您不希望这种行为,您可以探索为 404 响应创建自定义处理程序,this thread. You could also use a routing library like Gorilla which has overridable behavior 中针对未找到的页面对此进行了探索。