Node.js 从入门到茫然系列——入门篇

在创建服务的时候,我们一般代码就是:

var http = require("http");

var server = http.createServer(function(req,res){
    res.end("ok")
});

server.listen(3000)

目前我们最流行的就是逃出回调的约束,所以,我们换一种写法:

var http = require("http");

var server = http.createServer();
server.on('request',function(req,res){
    res.end("ok");
})

server.listen(3000)

设置头信息

res.writeHead(200,{   //返回请求状态
    'Content-type':'text/html',   // 实体的主体部分是什么
    'Set-Cookie':['user=futianyu','id=123456','password=369852147']  //设置私有 cookie 这里除了 Cookie内置的属性外,自定义多少个值就有多少个 cookie
});

设置头信息的时候,如果设置的状态是 302:

res.writeHead(302,{
    'Content-type':'text/html',
    "Location":"/a/index.html"
});

并且没有在对 “/a/index.html”这个页面做其它头信息的设置,则浏览器会报错 “重定向次数过多”。

很多时候我们还觉得经常写

res.writeHead(code,head);
res.write(str);
res.end();

挺烦的,这个时候我们真希望给 res 自定义一个函数,直接将状态以及要发送的内容,并且将响应给结束掉。这个时候我们可以给 “http.ServerResponse”添加属性。

http.ServerResponse.prototype.setResponseEnd = function(code,head){
    this.writeHead(code,head);
    this.write(str);
    this.end();
}
里面的 this 指向的就是 response 。可以随意添加了,express 也是这么做的哦,只是代码写的比我好看。在需要调用的地方直接调用
res.setResponseEnd()
 
原文地址:https://www.cnblogs.com/fws407296762/p/5398688.html