- Response
- Properties
- Methods
- res.append(field [, value])
- res.attachment([filename])
- res.cookie(name, value [,options])
- res.clearCookie(name [,options])
- res.download(path, [,filename], [,fn])
- res.end([data] [, encoding])
- res.format(object)
- res.get(field)
- res.json([body])
- res.jsonp([body])
- res.links(links)
- res.location(path)
- res.redirect([status,] path)
- res.render(view [, locals] [, callback])
- res.send([body])
- res.sendFile(path [, options] [, fn])
- res.sendStatus(statusCode)
- res.set(field [, value])
- res.status(code)
- res.type(type)
- res.vary(field)
Response
res对象代表了当一个HTTP请求到来时,Express程序返回的HTTP响应。在本文档中,按照惯例,这个对象总是简称为res(http请求简称为req),但是它们实际的名字由这个回调方法在那里使用时的参数决定。
例如:
app.get('/user/:id', function(req, res) {res.send('user' + req.params.id);});
这样写也是一样的:
app.get('/user/:id', function(request, response) {response.send('user' + request.params.id);});
Properties
res.app
这个属性持有express程序实例的一个引用,其可以在中间件中使用。res.app和请求对象中的req.app属性是相同的。
res.headersSent
布尔类型的属性,指示这个响应是否已经发送HTTP头部。
app.get('/', function(req, res) {console.log(res.headersSent); // falseres.send('OK'); // send之后就发送了头部console.log(res.headersSent); // true});
res.locals
一个对象,其包含了响应的能够反应出请求的本地参数和因此只提供给视图渲染,在请求响应的周期内(如果有的话)—我要翻译吐了。否则,其和app.locals是一样的。(不知道翻译的什么…)
这个参数在导出请求级别的信息是很有效的,这些信息比如请求路径,已认证的用户,用户设置等等。
app.use(function(req, res, next) {res.locals.user = req.user;res.locals.authenticated = !req.user.anonymous;next();});
Methods
res.append(field [, value])
res.append()方法在
Expresxs4.11.0以上版本才支持。
在指定的field的HTTP头部追加特殊的值value。如果这个头部没有被设置,那么将用value新建这个头部。value可以是一个字符串或者数组。
注意:在res.append()之后调用app.set()函数将重置前面设置的值。
res.append('Lind', ['<http://localhost>', '<http://localhost:3000>']);res.append('Set-Cookie', 'foo=bar;Path=/;HttpOnly');res.append('Warning', '199 Miscellaneous warning');
res.attachment([filename])
设置HTTP响应的Content-Disposition头内容为”attachment”。如果提供了filename,那么将通过res.type()获得扩展名来设置Content-Type,并且设置Content-Disposition内容为”filename=”parameter。
res.attachment();// Content-Disposition: attachmentres.attachment('path/to/logo.png');// Content-Disposition: attachment; filename="logo.png"// Content-Type: image/png
res.cookie(name, value [,options])
设置name和value的cookie,value参数可以是一串字符或者是转化为json字符串的对象。
options是一个对象,其可以有下列的属性。
|属性|类型|描述|
|:—-:|:—-:|:—-:|
|domain|String|设置cookie的域名。默认是你本app的域名。|
|expires|Date|cookie的过期时间,GMT格式。如果没有指定或者设置为0,则产生新的cookie。|
|httpOnly|Boolean|这个cookie只能被web服务器获取的标示。|
|maxAge|String|是设置过去时间的方便选项,其为过期时间到当前时间的毫秒值。|
|path|String|cookie的路径。默认值是/。|
|secure|Boolean|标示这个cookie只用被HTTPS协议使用。|
|signed|Boolean|指示这个cookie应该是签名的。|
res.cookie()所作的都是基于提供的
options参数来设置Set-Cookie头部。没有指定任何的options,那么默认值在RFC6265中指定。
使用实例:
res.cookie('name', 'tobi', {'domain':'.example.com', 'path':'/admin', 'secure':true});res.cookie('remenberme', '1', {'expires':new Date(Date.now() + 90000), 'httpOnly':true});
maxAge是一个方便设置过期时间的方便的选项,其以当前时间开始的毫秒数来计算。下面的示例和上面的第二条功效一样。
res.cookie('rememberme', '1', {'maxAge':90000}, "httpOnly":true);
你可以设置传递一个对象作为value的参数。然后其将被序列化为Json字符串,被bodyParser()中间件解析。
res.cookie('cart', {'items':[1, 2, 3]});res.cookie('cart', {'items':[1, 2, 3]}, {'maxAge':90000});
当我们使用cookie-parser中间件的时候,这个方法也支持签名的cookie。简单地,在设置options时包含signed选项为true。然后res.cookie()将使用传递给cookieParser(secret)的密钥来签名这个值。
res.cookie('name', 'tobi', {'signed':true});
res.clearCookie(name [,options])
根据指定的name清除对应的cookie。更多关于options对象可以查阅res.cookie()。
res.cookie('name', 'tobi', {'path':'/admin'});res.clearCookie('name', {'path':'admin'});
res.download(path, [,filename], [,fn])
传输path指定文件作为一个附件。通常,浏览器提示用户下载。默认情况下,Content-Disposition头部”filename=”的参数为path(通常会出现在浏览器的对话框中)。通过指定filename参数来覆盖默认值。
当一个错误发生时或者传输完成,这个方法将调用fn指定的回调方法。这个方法使用res.sendFile()来传输文件。
res.download('/report-12345.pdf');res.download('/report-12345.pdf', 'report.pdf');res.download('report-12345.pdf', 'report.pdf', function(err) {// Handle error, but keep in mind the response may be partially-sent// so check res.headersSentif (err) {} else {// decrement a download credit, etc.}});
res.end([data] [, encoding])
结束本响应的过程。这个方法实际上来自Node核心模块,具体的是response.end() method of http.ServerResponse。
用来快速结束请求,没有任何的数据。如果你需要发送数据,可以使用res.send()和res.json()这类的方法。
res.end();res.status(404).end();
res.format(object)
进行内容协商,根据请求的对象中AcceptHTTP头部指定的接受内容。它使用req.accepts()来选择一个句柄来为请求服务,这些句柄按质量值进行排序。如果这个头部没有指定,那么第一个方法默认被调用。当不匹配时,服务器将返回406“Not Acceptable”,或者调用default回调。Content-Type请求头被设置,当一个回调方法被选择。然而你可以改变他,在这个方法中使用这些方法,比如res.set()或者res.type()。
下面的例子,将回复{"message":"hey"},当请求的对象中Accept头部设置成”application/json”或者”/json”(不过如果是`/*`,然后这个回复就是”hey”)。
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() {res.status(406).send('Not Acceptable');}})
除了规范化的MIME类型之外,你也可以使用拓展名来映射这些类型来避免冗长的实现:
res.format({text:function() {res.send('hey');},html:function() {res.send('<p>hey</p>');},json:function() {res.send({message:'hey'});}})
res.get(field)
返回field指定的HTTP响应的头部。匹配是区分大小写。
res.get('Content-Type');// => "text/plain"
res.json([body])
发送一个json的响应。这个方法和将一个对象或者一个数组作为参数传递给res.send()方法的效果相同。不过,你可以使用这个方法来转换其他的值到json,例如null,undefined。(虽然这些都是技术上无效的JSON)。
res.json(null);res.json({user:'tobi'});res.status(500).json({error:'message'});
res.jsonp([body])
发送一个json的响应,并且支持JSONP。这个方法和res.json()效果相同,除了其在选项中支持JSONP回调。
res.jsonp(null)// => nullres.jsonp({user:'tobi'})// => {"user" : "tobi"}res.status(500).jsonp({error:'message'})// => {"error" : "message"}
默认情况下,jsonp的回调方法简单写作callback。可以通过jsonp callback name设置来重写它。
下面是一些例子使用JSONP响应,使用相同的代码:
// ?callback=foores.jsonp({user:'tobo'})// => foo({"user":"tobi"})app.set('jsonp callback name', 'cb')// ?cb=foores.status(500).jsonp({error:'message'})// => foo({"error":"message"})
res.links(links)
连接这些links,links是以传入参数的属性形式提供,连接之后的内容用来填充响应的Link HTTP头部。
res.links({next:'http://api.example.com/users?page=2',last:'http://api.example.com/user?page=5'});
效果:
Link:<http://api.example.com/users?page=2>;rel="next",<http://api.example.com/users?page=5>;rel="last"
res.location(path)
设置响应的LocationHTTP头部为指定的path参数。
res.location('/foo/bar');res.location('http://example.com');res.location('back');
当path参数为back时,其具有特殊的意义,其指定URL为请求对象的Referer头部指定的URL。如果请求中没有指定,那么其即为”/“。
Express传递指定的URL字符串作为回复给浏览器响应中的
Location头部的值,不检测和操作,除了当是back这个case时。浏览器有推导预期URL从当前的URL或者指定的URL,和在Location指定的URL的责任;相应地重定向它。(我也不知道翻译的什么…)
res.redirect([status,] path)
重定向来源于指定path的URL,以及指定的HTTP status codestatus。如果你没有指定status,status code默认为”302 Found”。
res.redirect('/foo/bar');res.redirect('http://example.com');res.redirect(301, 'http://example.com');res.redirect('../login');
重定向也可以是完整的URL,来重定向到不同的站点。
res.redirect('http://google.com');
重定向也可以相对于主机的根路径。比如,如果程序的路径为http://example.com/admin/post/new,那么下面将重定向到http://example.com/admim:
res.redirect('/admin');
重定向也可以相对于当前的URL。比如,来之于http://example.com/blog/admin/(注意结尾的/),下面将重定向到http://example.com/blog/admin/post/new。
res.redirect('post/new');
如果来至于http://example.com/blog/admin(没有尾部/),重定向post/new,将重定向到http://example.com/blog/post/new。如果你觉得上面很混乱,可以把路径段认为目录(有’/‘)或者文件,这样是可以的。相对路径的重定向也是可以的。如果你当前的路径为http://example.com/admin/post/new,下面的操作将重定向到http://example.com/admin/post:
res.redirect('..');
back将重定向请求到referer,当没有referer的时候,默认为/。
res.redirect('back');
res.render(view [, locals] [, callback])
渲染一个视图,然后将渲染得到的HTML文档发送给客户端。可选的参数为:
locals,定义了视图本地参数属性的一个对象。callback,一个回调方法。如果提供了这个参数,render方法将返回错误和渲染之后的模板,并且不自动发送响应。当有错误发生时,可以在这个回调内部,调用next(err)方法。
本地变量缓存使能视图缓存。在开发环境中缓存视图,需要手动设置为true;视图缓存在生产环境中默认开启。
// send the rendered view to the clientres.render('index');// if a callback is specified, the render HTML string has to be sent explicitlyres.render('index', function(err, html) {res.send(html);});// pass a local variable to the viewres.render('user', {name:'Tobi'}, function(err, html) {// ...});
res.send([body])
发送HTTP响应。body参数可以是一个Buffer对象,一个字符串,一个对象,或者一个数组。比如:
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' });
对于一般的非流请求,这个方法可以执行许多有用的的任务:比如,它自动给Content-LengthHTTP响应头赋值(除非先前定义),也支持自动的HEAD和HTTP缓存更新。
当参数是一个Buffer对象,这个方法设置Content-Type响应头为application/octet-stream,除非事先提供,如下所示:
res.set('Content-Type', 'text/html');res.send(new Buffer('<p>some html</p>'));
当参数是一个字符串,这个方法设置Content-Type响应头为text/html:
res.send('<p>some html</p>');
当参数是一个对象或者数组,Express使用JSON格式来表示:
res.send({user:'tobi'});res.send([1, 2, 3]);
res.sendFile(path [, options] [, fn])
res.sendFile()从Express v4.8.0开始支持。
传输path指定的文件。根据文件的扩展名设置Content-TypeHTTP头部。除非在options中有关于root的设置,path一定是关于文件的绝对路径。
下面的表提供了options参数的细节:
|属性|描述|默认值|可用版本|
|:—-:|:—-:|:—-:|:—-:|
|maxAge|设置Cache-Control的max-age属性,格式为毫秒数,或者是ms format的一串字符串|0||
|root|相对文件名的根目录|||
|lastModified|设置Last-Modified头部为此文件在系统中的最后一次修改时间。设置false来禁用它|Enable|4.9.0+|
|headers|一个对象,包含了文件所在的sever的HTTP头部。(不知道怎么翻译了)|||
|dotfiles|是否支持点开头文件名的选项。可选的值”allow”,”deny”,”ignore”|”ignore”||
当传输完成或者发生了什么错误,这个方法调用fn回调方法。如果这个回调参数指定了和一个错误发生,回调方法必须明确地通过结束请求-响应循环或者传递控制到下个路由来处理响应过程。
下面是使用了所有参数的使用res.sendFile()的例子:
app.get('/file/:name', function(req, res, next) {var options = {root:__dirname + '/public',dotfile:'deny',headers:{'x-timestamp':Date.now(),'x-sent':true}};var fileName = req.params.name;res.sendFile(fileName, options, function(err) {if (err) {console.log(err);res.status(err.status).end();}else {console.log('sent', fileName);}});});
res.sendFile提供了文件服务的细粒度支持,如下例子说明:
app.get('/user/:uid/photos/:file', function(req, res) {var uid = req.params.uid, file = req.params.file;req.user.mayViewFilesFrom(uid, function(yes) {if (yes) {res.sendFile('/upload/' + uid + '/' + file);}else {res.status(403).send('Sorry! you cant see that.');}});})
获取更多信息,或者你有问题或者关注,可以查阅send。
res.sendStatus(statusCode)
设置响应对象的HTTP status code为statusCode并且发送statusCode的相应的字符串形式作为响应的Body。
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')
如果一个不支持的状态被指定,这个HTTP status依然被设置为statusCode并且用这个code的字符串作为Body。
res.sendStatus(2000); // equivalent to res.status(2000).send('2000');
res.set(field [, value])
设置响应对象的HTTP头部field为value。为了一次设置多个值,那么可以传递一个对象为参数。
res.set('Content-Type', 'text/plain');res.set({'Content-Type':'text/plain','Content-Length':'123','ETag':'123456'})
其和res.header(field [,value])效果一致。
res.status(code)
使用这个方法来设置响应对象的HTTP status。其是Node中response.statusCode的一个连贯性的别名。
res.status(403).end();res.status(400).send('Bad Request');res.status(404).sendFile('/absolute/path/to/404.png');
res.type(type)
设置Content-TypeHTTP头部为MIME type,如果这个指定的type能够被mime.lookup确定。如果type包含/字符,那么设置Content-Type为type(我已经晕了)。
res.type('.html'); // => 'text/html'res.type('html'); // => 'text/html'res.type('json'); // => 'application/json'res.type('application/json'); // => 'application/json'res.type('png'); // => image/png:
res.vary(field)
设置Vary响应头为field,如果已经不在那里。(不懂什么意思)
res.vary('User-Agent').render('docs');
