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

koa源码分析(四) - response.js #8

Open
brunoyang opened this issue Oct 10, 2015 · 0 comments
Open

koa源码分析(四) - response.js #8

brunoyang opened this issue Oct 10, 2015 · 0 comments

Comments

@brunoyang
Copy link
Owner

本文分为四个部分,分别对应源码的四个文件。

依赖

大多数在之前有介绍到过,这里只讲之前没讲到的

  • vary: 用于设置vary字段

源码分析

首先,推荐大家去看http roc文档,这还是中文版的,不用怕看不懂。作为前端工程师,又跟node打交道,http知识是必不可少的,有兴趣的还应该再去了解TCP/IP协议,了解一点后就会对网络通信有比较深入的了解了,推荐一个大部头,《TCP-IP详解》,内容很多,调重要的看,绝对能学到很多。

照例,有些一眼看得懂的我又不讲啦。

set body

响应体(body)若为空,设状态码为204,并将Content-Type,Content-Length,Transfer-Encoding移除掉,因为这三个字段在body有值时才会被设置。
接着内容是不是由‘<’打头的字符串,若是的话就肯定是个html,若不是的话,就是个单纯的文本。
再判断是否为一个buffer也就是二进制文件,图片视频那些东西在传输时全是二进制,所以就不做啥操作,设置个length就行了。
然后看是否是stream,依据是是否有pipe这个函数,这个函数就跟管道符一样,用于传输数据,然后我就不太懂了。
最后就认为body是个json, json没有length

redirect

用法:

this.redirect('back');

this.redirect('back', '/index.html');

this.redirect('/login');

this.redirect('http://google.com');

若第一个参数为back,该方法将从referrer中取值或取第二个参数,没有就直接跳'/'。接着在看req中的accept是什么值,要是个html的话,body是个链接,若不是的话,直接返回串字符就行了。

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

1 participant