logo

Example of Sending Data to a Julia Server via Localhost in JavaScript 📂Programing

Example of Sending Data to a Julia Server via Localhost in JavaScript

Showcase

Clicking the left button sends the message ‘A’ and clicking the right button sends ‘B’ to the Julia server. The Julia server receives this message via the HTTP.jl package and, via , outputs it to the console.


Code

HTML

<button onclick="sendData('A')">Send 'A'</button>
<button onclick="sendData('B')">Send 'B'</button>
  • onclick: When the button is clicked, the sendData function is executed.

JavaScript

<script>
    function sendData(message) {
        fetch('http://localhost:8000', {
            method: 'POST',
            headers: { 'Content-Type': 'text/plain' },
            body: message
        });
    }
</script>
  • function sendData(message): accepts message as its input. In the example above, these were ‘A’ and ‘B’, respectively.
  • fetch('http://localhost:8000': transmits the data to the server at localhost port 8000. The Julia receiver must be bound to the same port.

Julia

Execute the server.jl file written as follows to receive the data.

using HTTP

const CORS_HEADERS = [
    "Access-Control-Allow-Origin" => "*",
    "Access-Control-Allow-Methods" => "POST, GET, OPTIONS",
    "Access-Control-Allow-Headers" => "Content-Type"
]
function handler(req::HTTP.Request)
    if req.method == "OPTIONS"
        return HTTP.Response(200, CORS_HEADERS)
    elseif req.method == "POST"
        body = String(req.body)
        println("Received:", body)
        return HTTP.Response(200, vcat(CORS_HEADERS, "Content-Type" => "text/plain"), 
                             "Server received: " * body)
    else
        return HTTP.Response(405, "Method Not Allowed")
    end
end

server = HTTP.serve(handler, "0.0.0.0", 8000)
  • const CORS_HEADERS: sets the CORS headers. This permits web pages from other origins to access this server.
  • HTTP.serve(handler, "0.0.0.0", 8000): listens for requests on localhost port 8000. The JavaScript sender must use the same port when sending.