gpt4 book ai didi

node.js - 如何使用 Express API 发送 10x 响应?

转载 作者:可可西里 更新时间:2023-11-01 16:32:11 26 4
gpt4 key购买 nike

我正在实现发送早期信息响应的过程。这是我正在尝试优化的功能 h2o's push response feature described here (Ctrl+F for Server Push) .

我一直在寻找一个理智的 Express API 来允许刷新像这样的早期 100 响应:

HTTP/1.1 100 Continue
Link: </assets/layout.css>; rel=preload; as=style
...

HTTP/1.1 200 OK
....

可惜没找到。我也在寻找合适的 Node 响应 API,但我唯一能找到的是复制粘贴 Node 的 writeContinue 内部解决方案,如下所示:

const common = require('_http_common')
const { CRLF } = common
let links = []

// fill up links

const earlyResponse = 'HTTP/1.1 100 Continue' + CRLF + links.map(link => `Link: ${link}`).join(CRLF) + CRLF + CRLF

res._writeRaw(earlyResponse, 'ascii', () => {
res.status(200)send("blabla")
})

这种感觉很脏,因为 _writeRaw 似乎是私有(private) API,所以我想知道在那里注入(inject)早期响应的最干净的方法是什么。

这是 in the process of being standardized under the 103 code ,因此了解如何实现这一点很重要。

最佳答案

(请参阅下面的更新以了解将自定义 header 添加到 100 Continue 的方法)

如果请求中有 Expect: 100-continue header ,Express 会自动发送 100 Continue

看例子:

const app = require('express')();
app.get('/', (req, res) => {
console.log('xxx');
res.json({ xxx: 1 });
});
app.listen(4433);

并发送一个请求:

$ echo -ne 'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n' | nc localhost 4433
HTTP/1.1 100 Continue

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 9
ETag: W/"9-8rjb3nqDuC81Vbxmadwj3RqLz9Y"
Date: Wed, 19 Jul 2017 11:21:47 GMT
Connection: keep-alive

{"xxx":1}

如你所见,有:

HTTP/1.1 100 Continue

即使在 Express 应用中没有进行特殊配置,也会出现在响应中。

您还可以显式发送 Continue:

res.writeContinue();

但添加自定义 header 可能很困难 - 请参阅此问题:

更新

上面的示例更新了一些,但我认为这是让它工作的唯一方法 - 感谢 Robert Klep 在评论中发布它:

const app = require('express')();
app.get('/', (req, res) => {
console.log('xxx');
res.json({ xxx: 1 });
});
let server = app.listen(4433);
server.on('checkContinue', (req, res) => {
res._writeRaw('HTTP/1.1 100 Continue\r\nFoo: bar\r\n\r\n');
res._sent100 = true;
server.emit('request', req, res);
});

现在的响应是:

$ echo -ne 'GET / HTTP/1.1\r\nExpect: 100-continue\r\n\r\n' | nc localhost 4433
HTTP/1.1 100 Continue
Foo: bar

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 9
ETag: W/"9-8rjb3nqDuC81Vbxmadwj3RqLz9Y"
Date: Wed, 19 Jul 2017 12:17:18 GMT
Connection: keep-alive

{"xxx":1}

这是 Robert Klep 的原始 Gist:

关于node.js - 如何使用 Express API 发送 10x 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45188813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com