pythonhtmlhttp.server

Python server showing html as text rather than rendering it


I'm trying to make a server the long way for more control/ learning. when i try to make a simple one with bash i get mimetype errors.

I must be looking at this the wrong way but my server seems to make the browser render the html as text. the html i get in the browser is weird too.

any help would be mush appreciated!

server.py

from http.server import HTTPServer,BaseHTTPRequestHandler

HOST = "localhost"
PORT = 7800

class FeedSpeedServer(BaseHTTPRequestHandler):

    def do_GET(self):


        if self.path == "/":
            self.path = 'index.html'
        
        try:
            
            self.send_header("content-type", "text/html")
            self.send_header("content-type", "text/javascript")
            self.send_header("content-type", "text/css")
            self.end_headers()
            self.file = open(self.path).read()
            self.wfile.write(self.file.encode())
            self.send_response(200)
            
        except:
            self.file = "file not found"
            self.send_response(404)


httpd = HTTPServer((HOST, PORT), FeedSpeedServer)
print("server running...")
httpd.serve_forever()
print("server Stopped")

My web browser shows this...

screenshot


Solution

  • Ok - Figured it out.

    So i was having problems with MIME types and java script modules. I have thrown away the server i tried making and found it way easier to just use simple http.server.SimpleHTTPRequestHandler this post fixed everything for me - Failed to load module script: The server responded with a non-JavaScript MIME type of "text/plain"

    Also, put .js on the end of your import paths like this:

    import { FeedsSpeeds } from "./FeedsSpeeds.js";