Node.js 如何使用Express API发送10倍的响应?
我正在实施发送早期信息响应的过程中。这是我试图优化的一个特性 我正在寻找一个sane Express API,以允许刷新早期100响应,如下所示:Node.js 如何使用Express API发送10倍的响应?,node.js,http,express,reverse-proxy,Node.js,Http,Express,Reverse Proxy,我正在实施发送早期信息响应的过程中。这是我试图优化的一个特性 我正在寻找一个sane Express API,以允许刷新早期100响应,如下所示: HTTP/1.1 100 Continue Link: </assets/layout.css>; rel=preload; as=style ... HTTP/1.1 200 OK .... 这种感觉很糟糕,因为writeRaw似乎是私有API,所以我想知道在那里注入早期响应的最干净的方法是什么 这是,所以知道如何完成这一点很重要
HTTP/1.1 100 Continue
Link: </assets/layout.css>; rel=preload; as=style
...
HTTP/1.1 200 OK
....
这种感觉很糟糕,因为writeRaw似乎是私有API,所以我想知道在那里注入早期响应的最干净的方法是什么
这是,所以知道如何完成这一点很重要 (有关将自定义标题添加到100 Continue
的方法,请参见下面的更新)
如果请求中有Expect:100 Continue
标题,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();
但添加自定义标题可能很困难-请参阅此问题:
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的原始要点:
$ 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}