HTTP.jl + Ajax

Where can I find a simple example of a HTTP.jl backend server and a HTML+Javascript FE?
I want to learn to communicate between Javascript and Julia for a simple app. Example: I would like to create a html input which takes a number x, uses Ajax to send the number to the Julia backend and then returns x^2 in another html text, so I need to both serve and listen. The examples from HTTP.jl github page are separated between serve and listen.

I would like to do this barebones, without the aid of other frameworks like Genie or Dash.

Check out


Thank you very much for your fast reply! Let’s say I save the html/javascript part to an index.html file. How can I serve that page? The example I used was:

HTTP.serve() do request::HTTP.Request
       return HTTP.Response(200, read(raw"C:\myapp\index.html"))
   catch e
       return HTTP.Response(404, "Error: $e")

But I don’t know how to adapt your example to that.

Thank you once more for your support!

Register another route for GET /index.html, and the routed function will return the html content.

1 Like

It worked! Thanks! The code:

using HTTP, JSON

const ROUTER = HTTP.Router()

function square(req::HTTP.Request)
    headers = [
        "Access-Control-Allow-Origin" => "*",
        "Access-Control-Allow-Methods" => "POST, OPTIONS"
    # handle CORS requests
    if HTTP.method(req) == "OPTIONS"
        return HTTP.Response(200, headers)
    body = parse(Float64, String(HTTP.body(req)))
    square = body^2
    HTTP.Response(200, headers; body = string(square))

function render(req::HTTP.Request)
    HTTP.Response(200, read(raw"C:\index2.html"))

HTTP.@register(ROUTER, "POST", "/api/square", square)
HTTP.@register(ROUTER, "GET", "/index2.html", render)

HTTP.serve(ROUTER, "", 8080)
1 Like