简体   繁体   English

使用Express发送故意无效的HTTP响应

[英]Send intentionally invalid HTTP response with Express

I'm building a few tests for a web app and I'd like to test the ability of the client to gracefully handle invalid HTTP responses. 我正在为Web应用程序构建一些测试,我想测试客户端优雅地处理无效HTTP响应的能力。 How do you suggest mangling a response such that it's not longer valid? 您如何建议修改响应使其不再有效? I tried the following but Express evidently fixed the Content-Length afterwards: 我尝试了以下方法,但Express之后显然修复了Content-Length

app.get('/broken/', function(req, res) {
    console.log('request received for ' + req.path);
    res.set('Content-Length', 0).send('more than zero');
});

EDIT: To note, I'm not necessarily in control of the incoming requests. 编辑:要注意,我不一定控制传入的请求。 In the past some of them have been invalid. 在过去,其中一些无效。

Indeed, Express resets Content-Length inside response.send method. 实际上, Express重置了response.send方法中的Content-Length

if (chunk !== undefined) {
  len = chunk.length;
  this.set('Content-Length', len);
}

Basically, send does nothing more than setting a bunch of headers and delegating the rest of work to http.ServerResponse.end . 基本上, send只是设置一堆标题并将其余工作委托给http.ServerResponse.end而已

In order to bypass this behaviour, you could use end method directly. 为了绕过此行为,您可以直接使用end方法。

app.get('/broken/', function(req, res) {
  res.set('Content-Length', 0)
     .set('Content-Type', type);
     .end('more than zero');
});

I think the right answer (even if you can work around it) is to not use a HTTP client for this. 我认为正确的答案(即使您可以解决)也不要为此使用HTTP客户端。 Any HTTP client would make an effort to prevent you from making invalid HTTP calls. 任何HTTP客户端都会努力防止您进行无效的HTTP调用。 The correct answer therefore is to make an intentionally non-conforming HTTP client, which implies you need to dive down to writing tcp sockets. 因此,正确的答案是制作一个故意不合格的HTTP客户端,这意味着您需要深入研究编写tcp套接字。 Even if this means that this doesn't fully fit in your testing framework, I presume that you only need this for one test. 即使这意味着它不能完全适合您的测试框架,我还是假设您只需要一个测试即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM