python - 通过 python 套接字服务器发送 css

标签 python html sockets

我创建了一个小型 python html 服务器,但我在发送外部 css 和 javascript 时遇到问题。 html 传输正常,内联 css 工作正常。 chrome 开发人员工具响应此错误:

Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost:8888/style.css".

不幸的是,我不知道什么是“MIME 类型”。

这是python代码:

# server.py
import socket

file = open('website/index.html', 'r')

def start_server(HOST, PORT):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((HOST, PORT))
    s.listen(1)

    print('Serving HTTP on port %s ...' % PORT)
    while True:
        client_connection, client_address = s.accept()
        request = client_connection.recv(1024)
        print(request.decode('utf-8'))

        http_response = """\
http/1.1 200 OK

""" + file.read() + """
"""
        client_connection.sendall(bytes(http_response, 'utf-8'))
        client_connection.close()

最佳答案

将此行添加到 200 OK 行正下方的响应字符串中:

Content-Type: text/css

发生的事情是 Chrome 试图将您发送的 HTML 解释为您想要的样式表。但是,当你发送它时,你发送的是一个内容标题,它告诉 chrome “我只是纯文本,这里没有什么特别的!”所以 Chrome 就像,好吧,它有问题,我期待一个样式表,并抛出你看到的错误。如果您告诉 Chrome 您正在向它发送样式表,则该错误应该得到解决。

This is from Mozilla rather than Chrome, but it gives a good overview of MIME types.

关于python - 通过 python 套接字服务器发送 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38861763/

相关文章:

python - 可拖动线在 Matplotlib 中相互选择

python - Gensim 的 Doc2vec - 推断的向量不相似

Python 的每个循环不起作用

javascript - 使用 Bootstrap 4 超大屏幕类时的图像轮播

无法从另一台计算机访问 Windows 7 上的 Python 套接字

python - 对未知秩的张量应用函数(平均倒数秩)

html - 具有相同高度的CSS Flex-Box

html - 垂直居中对齐文本

java - 尝试加快 java 中 Socket 的读取速度

c# - .NET 中的套接字 - 多线程服务器入门