【发布时间】:2023-03-26 18:20:01
【问题描述】:
尝试在来自 node.js http.createServer 的请求事件中使用异步函数。我想使用 vanilla node.js 模块。 我知道我可以使用外部依赖项,但希望在没有理想情况下解决。
我不明白为什么我从 console.logs 中看到的异步函数取回数据,但 curl resp 不包含它。我没有收到任何错误,比如在 resp 发回后写标题很困惑为什么 curl 没有 { data: 1 } 的正文。如果我删除 async/await 并将 req.end 硬编码为“测试”,它会在 curl 请求中返回。
server.js
const server = http.createServer();
server.on('request', async (req, res) => {
const data = await someAsyncFunc();
console.log(req.url);
console.log(data);
res.end(JSON.stringify(data));
});
终端
curl localhost:3000/test -v
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to localhost (127.0.0.1) port 3000 (#0)
> GET /test HTTP/1.1
> Host: localhost:3000
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 404 Not Found
< Content-Type: text/plain; charset=utf-8
< Content-Length: 9
< Date: Tue, 17 Apr 2018 18:44:00 GMT
< Connection: keep-alive
<
* Connection #0 to host localhost left intact
Not Found%
server.js 日志
/test
{ data: 1 }
----- 更新 ------
似乎这个问题的原因是我将 koa app.callback() 传递给 createServer,这似乎破坏了 http 服务器请求事件中的异步内容:
const app = new Koa();
http.createServer(app.callback());
我更喜欢使用 server.on('request') 但我可以让它工作的唯一方法是使用 koa 中间件。
【问题讨论】:
-
什么是
someAsyncFunc?您正在将 that 的结果打印到控制台,它不是来自请求 -
也许你应该在结束前写下响应头:
res.writeHead(200, {"Content-Type": "your content MIME"})(代码200表示OK) -
看起来服务器没有这样的路由
GET /test,甚至在你的代码执行之前你就得到了 404... -
...如果
someAsyncFunc花费很长时间,客户端可能会收到连接超时错误。 -
只要
someAsyncFunc()返回一个可以解析为您的值的承诺,server.js 中的代码就可以找到。真的是这样吗?也许您应该向我们展示someAsyncFunction()的代码,因为这就是更有趣的事情发生的地方。
标签: javascript node.js http async-await