我正在尝试在 Julia 中启动一个简单的服务器。 (Julia 1.7、HTTP v0.9.16、Windows 10)。
通过复制 HTTP 文档中的代码片段,我编写了
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
在 Julia 终端中。
当我在 Chrome 中导航到 http://localhost:8000/
时,它确实显示了一个带有“Helllllo”一词的页面。
但是,当我尝试向它发送 GET 请求时,它没有应答。我尝试过的事情:
打开新的 julia 终端并写入
using HTTP r = HTTP.request("GET", "https://127.0.0.1:8000");
发生的情况是该命令挂起,而不是生成 r
。
进入 Chrome 控制台并编写
fetch("https://127.0.0.1:8000") .then(res => res.json()) .then(console.log)
同样,没有答案。
我做错了什么?
谢谢!
最佳答案
几个不同的问题:
- 在设置普通
http
服务器后,您正尝试从https
地址读取数据。解决此问题后,Julia 就能够获得请求-响应:
julia> r = HTTP.request("GET", "http://127.0.0.1:8000")
HTTP.Messages.Response:
"""
HTTP/1.1 200 OK
Transfer-Encoding: chunked
Helllllo"""
- 但它在浏览器中仍然失败(在 Firefox 中 - 我认为在 Chrome 中也是如此)
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).
这只是因为 127.0.0.1 != localhost for browser , for security purposes (因此,当您位于 localhost
上时,它不允许您从 127.0.0.1
上的“不同”主机读取数据)。如果您这样做:
>> 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 }
关于http - 为什么本地主机上的 Julia 服务器挂起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70144544/