자바스크립트에서 로컬호스트를 통해 줄리아 서버로 데이터 전송하는 예제
쇼케이스
왼쪽 버튼을 클릭하면 ‘A’라는 메시지를, 오른쪽 버튼을 클릭하면 ‘B’라는 메시지를 줄리아 서버로 전송한다. 줄리아 서버는 HTTP.jl 패키지를 통해 이 메시지를 받아서serve 콘솔에 출력한다.
코드
HTML
<button onclick="sendData('A')">Send 'A'</button>
<button onclick="sendData('B')">Send 'B'</button>
onclick
: 버튼이 클릭되면sendData
함수가 실행된다.
javascript
<script>
function sendData(message) {
fetch('http://localhost:8000', {
method: 'POST',
headers: { 'Content-Type': 'text/plain' },
body: message
});
}
</script>
function sendData(message)
:message
를 입력으로 받는다. 위 예시에서는 각각 ‘A’와 ‘B’였다.fetch('http://localhost:8000'
: 로컬호스트 8000번 포트에 있는 서버로 데이터를 전송한다. 줄리아에서 받아줄 때도 같은 포트번호를 사용해야한다.
julia
다음과 같이 작성된 server.jl
파일을 실행해서 데이터를 수신한다.
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
: CORSCross-Origin Resource Sharing 헤더를 설정한다. 이는 다른 출처의 웹 페이지가 이 서버에 접근할 수 있도록 허용하는 것이다.HTTP.serve(handler, "0.0.0.0", 8000)
: 로컬호스트 8000번 포트에서 리퀘스트를 받아주고 있다. 자바스크립트에서 보낼 때도 같은 포트번호를 사용해야 한다.