简体   繁体   中英

How do you use the http.server python module to run HTML+Javascript+CSS?

I am trying to create a simple python server using the http.server module. My python code looks like this:

from http.server import HTTPServer, BaseHTTPRequestHandler

class helloHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.path == '/mainprogram.html'
        try:
            file_to_open = open('mainprogram.html').read()
            self.send_response(200)
        except:
            file_to_open = "file not found"
            self.send_response(404)
        self.send_header('content-type', 'text/html')
        self.end_headers()
        self.wfile.write(bytes(file_to_open, 'utf-8'))

def main():
    PORT = 8000
    server = HTTPServer(('', PORT),helloHandler)
    print('Server running on port %s' % PORT)
    server.serve_forever()

if __name__ == "__main__":
    main()

This serves my HTML page on the server but it doesn't run my javascript and CSS files. So the skeleton of my page is there ie text, buttons, search bars but none of the functionality is there and the styles aren't applied.

I have written separate CSS and Javascript files and have included them in my HTML file like this:

<link rel="stylesheet" href="styles.css">
<script src="scriptfile.js"><script>

Please help! I am a beginner to all this so I have no clue

Everything are explained here: https://morioh.com/p/8f241f0579b6

the link has a way to write the code makes it catch all the files and it very very well explained

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM