http - 无法加载样式表

标签 http crystal-lang

我正在尝试使用 Crystal 编写一个简单的网站。我有一个名为 assets 的文件夹,其中包含 index.htmlstyle.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

火狐:

enter image description here

最佳答案

您实际上永远不会复制 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/

相关文章:

compiler-errors - 生成/ fork : Cannot allocate memory中的Crystal未处理的异常

crystal-lang - `File.info(string)/File::Info.new(string)` 是否解析符号链接(symbolic link)?

http - 绕过 golang http 处理程序

node.js - 禁用保持事件状态时 Node http 服务器 4 x FASTER?

Arduino MKGSM 中的 HTTP POST 到 Eventhub

crystal-lang - 哈希。包括?在 Crystal 中给出奇怪的结果

crystal-lang - Crystal 中的速记 block 语法

crystal-lang - 遍历数组并返回自身

Angular 阻塞(同步)http 调用

http - Curl/Guzzle - 获取没有正文的标题/响应代码