http.createServer on('request') 异步/等待函数

Lab*_*tis 4 javascript http node.js async-await

尝试在来自 node.js http.createServer 的请求事件中使用异步函数。我想使用 vanilla node.js 模块。我知道我可以使用外部依赖项,但希望在没有理想情况下解决。

我不明白为什么我从 console.logs 看到的 async 函数中取回数据,但 curl resp 不包含它。我没有收到任何错误,比如在 resp 被发回后写标题,所以很困惑为什么 curl 没有{ data: 1 }. 如果我删除 async/await 并将 req.end 硬编码为“测试”,它会在 curl 请求中返回。

服务器.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));
});
Run Code Online (Sandbox Code Playgroud)

终端

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%
Run Code Online (Sandbox Code Playgroud)

server.js 日志

/test
{ data: 1 }
Run Code Online (Sandbox Code Playgroud)

-----更新------

似乎这个问题的原因是我将一个 koa app.callback() 传递给 createServer,这似乎在 http 服务器的请求事件中破坏了异步内容:

const app = new Koa();
http.createServer(app.callback());
Run Code Online (Sandbox Code Playgroud)

我更喜欢使用 server.on('request') 但我可以让它工作的唯一方法是使用 koa 中间件。

jfr*_*d00 8

我无法重现您的问题。

我发布这个作为答案只是为了与您分享我用来尝试重现您的问题的确切代码,以向您展示什么对我有用。

您的实际代码中必须有一些与此不同的内容导致错误,或者您的 curl 请求实际上并没有连接到您认为的服务器。您必须与我们分享更多信息,以便我们能够进一步提供帮助。您在问题中显示的代码不是问题。这是我使用的对我来说很好用的东西:

const http = require('http');

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));
});

function someAsyncFunc() {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve({data: 1});
        }, 1000);
    });
}

server.listen(3000);
Run Code Online (Sandbox Code Playgroud)

然后,我得到这个输出:

curl localhost:3000/test -v
*   Trying ::1...
* TCP_NODELAY set
*   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.59.0
> Accept: */*
>
< HTTP/1.1 200 OK
< Date: Tue, 17 Apr 2018 23:53:32 GMT
< Connection: keep-alive
< Content-Length: 10
<
{"data":1}* Connection #0 to host localhost left intact
Run Code Online (Sandbox Code Playgroud)