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

3 Likes

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
   try
       return HTTP.Response(200, read(raw"C:\myapp\index.html"))
   catch e
       return HTTP.Response(404, "Error: $e")
   end
end

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)
    end
    body = parse(Float64, String(HTTP.body(req)))
    square = body^2
    HTTP.Response(200, headers; body = string(square))
end

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

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

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