[NODE之16]express框架response

来源:互联网 发布:python progressbar 编辑:程序博客网 时间:2024/05/22 00:18
/** * Created by liyanq on 17/3/29. * http.ServerResponse 类 * 这个类非常重要,是给客户端的数据的重要通道。 * 计划分两部分:原生的对象和express框架下的对象。 *//*express下response对象 * 通过源码可以看出,express下response对象只是扩展了原型对象, * 这个对象只能通过express的方法得到,如get,post等.所以说,原生的方法都支持. * var res = module.exports = { *     __proto__: http.ServerResponse.prototype * }; * * 1,继承:res:ServerResponse->OutgoingMessage->Stream->EventEmitter 和原生的一样 * 2,个人感觉扩展的意义并不大,除了下面4个重点内容~ * * * 方法: * 1,status:->可以链式,返回引用~ * res.status(200) 等效 res.statusCode=200 * * 2,links:不知道干什么用的~ * 3,res.send([body])->(重点1:比原生支持了json) *   错误1:一次响应只能用一次这个函数,用两次的话:Error: Can't set headers after they are sent. *   错误2:用send发送完,不能再write写信息,否则:Error: write after end *   错误3:用write写完信息,也不能用send,否则:Error: Can't set headers after they are sent. * *   能够发送各种响应体,如下: *   res.send(new Buffer('whoop')); *   res.send({ some: 'json' }); *   res.send('<p>some html</p>'); *   res.status(404).send('Sorry, we cannot find that!'); *   res.status(500).send({ error: 'something blew up' }); * * 4,res.json([body])->发送一个 JSON 格式的响应。 * 5,res.jsonp:发送一个支持 JSONP 的 JSON 格式的响应。 *   没试验出来,查了下,是为了支持跨域请求,以后再说吧~ * * 6,res.sendStatus:设置响应状态代码,并将其以字符串形式作为响应体的一部分发送。 *   注意的是,这个方法里面调用了send方法,send方法的注意点对它都适合~ * res.sendStatus(200); // equivalent to res.status(200).send('OK') * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') * * 7,sendFile(path, options, callback):以八位字节流的形式发送文件。(重点2:原生没这个~) *   注意的是,sendFile内部也调用了res.end(),所以send方法的注意点对它都适合~ *   还有就是path参数是文件的绝对路径,包括文件名。 *   单独的sendFile也能处理完这次的响应,也能触发finish事件,不用再res.end()了。 * * 8,res.download(path [, filename] [, fn]):提示下载文件。(重点3:原生没这个~) *   注意的是,内部调用了sendFile,所以sendFile注意点它都适合。 * *   sendFile和download的区别: *   1,浏览器收到sendFile的文件会直接打开(适合的大小和类型),而download则都是用浏览器下载. *   2,download能命名下载文件的名字。 * * 9,res.contentType =res.type = function contentType(type):就是给设置Content-Type头信息提供了一个属性。 *   返回内容的MIME类型;如:Content-Type: text/html; charset=utf-8 * * 10,format:function(obj):根据Content-Type类型做出响应~ * 11,attachment: Content-disposition 是 MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件。 *    当 Internet Explorer 接收到头时,它会激活文件下载对话框,它的文件名框自动填充了头中指定的文件名。 *    (请注意,这是设计导致的;无法使用此功能将文档保存到用户的计算机上,而不向用户询问保存位置。) *    http://www.cnblogs.com/brucejia/archive/2012/12/24/2831060.html *    注意的是,执行send后,就不能再执行attachment函数了,但可以先执行send(); * 12,append:追加头信息 * 13,res.set = res.header = function header(field, val) * * 14,res.clearCookie = function clearCookie(name, options) { *       var opts = merge({ expires: new Date(1), path: '/' }, options); *       return this.cookie(name, '', opts); *    }; *    注意的是,不能清除或设置Set-Cookie设置的值,如果浏览器里面没有name的cookie, *             那么会新建个cookie,只是有效期是1970年~ * * 15,res.cookie = function (name, value, options) * 16,res.location = function location(url):设置头的location的值. * 16,res.redirect([status,] path):做跳转;(重点4:原生没这个~) * *   */var express = require("express");var path = require("path");var application = express();application.get("/", function (req, res) {    res.on("finish", function () {        console.log("下载完成");    });    res.status(200);    /*这三个不冲突,浏览器有三个相同名字的cookie~*/    res.append('Set-Cookie', 'foo=bar2; Path=/; HttpOnly');    res.cookie("foo",{name:"Hello Cookie"});    res.clearCookie("foo");    res.location("http://www.baidu.com");//设置值    res.redirect("http://www.baidu.com");//跳转    /*     const options = {     root: path.join(__dirname, "public"),     dotfiles: 'deny',     headers: {     'x-timestamp': Date.now(),     'x-sent': true     }     };     res.sendFile("buffer.rmvb", options,function () {     console.log("35.jpg下载完成");     // res.end();可以不加     });     res.download("public/35.jpg", "newDownload.jpg", function () {     console.log("newDownload.jpg下载完成");     // res.end();可以不加     });*/    /*res.contentType("text/html");    res.setHeader("Content-Disposition","attachment;filename=fileName.jpg");    res.format({        'text/plain': function () {            res.send('hey');        },        'text/html': function () {            res.send('<p>hey</p>');        },        'application/json': function () {            res.send({message: 'hey'});        },        'default': function () {            // log the request and respond with 406            res.status(406).send('Not Acceptable');        }    });*/    res.end();});var server = application.listen(3000, function () {    var host = server.address().address;    var port = server.address().port;    console.log('Example app listening at http://%s:%s', host, port);});

0 0