rscarth
rscarth

Reputation: 85

Send css over python socket server

I have created a small python html server, but I am having issues sending external css and javascript. The html transfers as it should and inline css works fine. The chrome developer tool responds with this error:

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

Unfortunately I have no knowledge on what a "MIME type" is.

Here is the python code:

# 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()

Upvotes: 3

Views: 3040

Answers (1)

James
James

Reputation: 2731

Add this line to your response string right beneath the 200 OK line:

Content-Type: text/css

What's happening is that Chrome is attempting to interpret the HTML you sent as as stylesheet, which you want. But, when you send it, you're sending with a content header that's telling chrome "I'm just plain text, nothing special here!" So Chrome is like, well something is wrong with that, I was expecting a stylesheet, and throws the error you see. If you tell Chrome that you're sending it a stylesheet, the error should be resolved.

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

Upvotes: 2

Related Questions