Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why use res.writeHead(proxyRes.statusCode); #2

Open
leotian opened this issue Jun 13, 2018 · 3 comments
Open

Why use res.writeHead(proxyRes.statusCode); #2

leotian opened this issue Jun 13, 2018 · 3 comments

Comments

@leotian
Copy link

leotian commented Jun 13, 2018

既然已经使用proxyRes.pipe(res)了,为什么还要在前面加个res.writeHead(proxyRes.statusCode);呢?

@wuchangming
Copy link
Owner

// 设置客户端响应的http头部
Object.keys(realRes.headers).forEach(function(key) {
    res.setHeader(key, realRes.headers[key]);
});

// 设置客户端响应状态码
res.writeHead(realRes.statusCode);

// 通过pipe的方式把真正的服务器响应内容转发给客户端
realRes.pipe(res);

如果不手动设置 status ,header 。只使用 realRes.pipe(res), 客户端无法获取真正服务器返回的status ,header

@leotian
Copy link
Author

leotian commented Jun 14, 2018

好的,多谢,我试过确实是这样的,但是不太明白为什么realRes.pipe(res)不能把realRes的所有内容都流入到res呢,statusCode不也是从realRes取出来又塞进去res的吗

@wuchangming
Copy link
Owner

@leotian ,可能一般场景都是只要内容,所以这么设计的吧。比如把响应内容直接写入某个文件,这个时候把status和header也写进去了,那就有点奇怪。用来做转发的需求是比较少的。

stackoverflow 上关于这点的问题答案:https://stackoverflow.com/a/29199616

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants