我正在尝试使用 Crystal 编写一个简单的网站。我有一个名为 assets
的文件夹,其中包含 index.html
、style.css
和一些图像。
当我尝试加载网站时,我可以访问 index.html
,但没有其他任何效果。 Firefox 报告 style.css 错误,并表示图像已损坏。
Server.cr
require "http/server"
class LieServer
def initialize(p : Int)
port = p
@server = HTTP::Server.new("127.0.0.1", port, [
HTTP::ErrorHandler.new,
HTTP::LogHandler.new,
HTTP::CompressHandler.new,
]) do |context|
resp = context.response
if context.request.path == "/" && context.request.method == "GET"
resp.content_type = "text/html"
File.open("./assets/index.html") do |file|
IO.copy(file, resp)
end
elsif (context.request.path == "/assets/sad.jpg" || context.request.path == "/assets/fireworks.jpg")
resp.content_type = "image"
elsif context.request.path == "/assets/style.css"
resp.content_type = "text/css"
else
resp.respond_with_error(message = "/", code = 404)
end
end
end
def start
puts "listening on http://localhost:#{@server.port}"
@server.listen
end
end
火狐:
最佳答案
您实际上永远不会复制 css 文件作为响应。只需设置内容类型。尝试将 css elsif block 更改为:
elsif context.request.path == "/assets/style.css"
resp.content_type = "text/css"
File.open("./assets/style.css") do |file|
IO.copy(file, resp)
end
else
.
.
.
顺便说一句,您的图像遇到了同样的问题。
关于http - 无法加载样式表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42913695/