Search code examples
javascriptpythonsimplehttpserver

Website: Send data from javascript (client) to python (server)


I have wrote a website using html/css and javascript and I am running this site using a simple python script

import http.server
import socketserver

PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

the website is running just fine. However I am trying to understand how can I send data from the js client to the python server? Let's settle a simple example. Let's assume that I have a simple html text input and a simple html button and I am writing some text to the field, how am I supposed to send this text, when I am pressing the button, to the server?

NOTE: I am using pure javascript so far


Solution

  • You should implement in Python a handler that can handle a POST or a PUT request onto a given URL. And in javascript, you just send your HTTP request on this URL with the correct HTTP method and with data in the body of your request.