I'm trying to start a simple server in Julia. (Julia 1.7, HTTP v0.9.16, Windows 10).
By copying the snippet in the HTTP docs, I've written
using HTTP
using Sockets
HTTP.serve(Sockets.localhost, 8000) do request::HTTP.Request
@show HTTP.header(request, "Content-Type")
@show HTTP.payload(request)
return HTTP.Response("Helllllo")
end
in a julia terminal.
When i navigate to http://localhost:8000/
in Chrome, it Does show a page with the word "Helllllo".
But, when i try to send GET requests to it, it doesn't answer. Things I tried:
Opening a new julia terminal and writing
using HTTP r = HTTP.request("GET", "https://127.0.0.1:8000");
What happens is that this command hangs, instead of producing a r
.
Going in Chrome console and writing
fetch("https://127.0.0.1:8000") .then(res => res.json()) .then(console.log)
Again, no answer.
What am I doing wrong?
Thanks!
CodePudding user response:
A couple different issues:
- You're trying to read from a
https
address, after having set up a plainhttp
server. Once you fix this, Julia is able to get a request-response:
julia> r = HTTP.request("GET", "http://127.0.0.1:8000")
HTTP.Messages.Response:
"""
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Helllllo"""
- But it still fails in the browser (in Firefox - I assume it will be the same in Chrome) with
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:8000/. (Reason: CORS request did not succeed).
This is simply because 127.0.0.1 != localhost for browser, for security purposes (so it doesn't allow you to read from the "different" host at 127.0.0.1
while you're on localhost
). If you instead do:
>> fetch("http://localhost:8000")
.then(console.log)
Promise { <state>: "pending" }
Response { type: "basic", url: "http://localhost:8000/", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: false }