您的位置:首页 > Web前端 > Node.js

Nodejs Express 4.X 中文API 3--- Response篇

2016-09-25 12:20 459 查看
 
本篇是Express 4.0 API翻译的第三篇,本篇的内容主要是Response的相关操作。


res.status(code)

支持连贯调用的node’s的 res.statusCode = 的别名。

1 res.status(404).sendfile('path/to/404.png');


res.set(field,[value])
设置请求头的字段为指定的值,或者通过一个对象一次设置多个值。

1 res.set('Content-Type','text/plain');
2
3 res.set({
4    'Content-Type':'text/plain',
5    'Content-Length':'123',
6    'ETag':'12345'
7 });


别名为:res.header(field,[value]); 。

 res.get(field)

获取不区分大小写的响应头 “field”(字段)。

1 res.get('Content-Type');
2 //=>"text/plain"


res.cookie(name,value,[options])

设置cookie name 的值为 value,接受参数可以一个字符串或者是对象转化成的JSON,path 默认设置为’/’。

1 res.cookie('name','tobi',{domain:'.example.com',path:'/admin',secure:true});
2 res.cookie('rememberme','1',{expires:new Date(Date.now() + 900000),httpOnly:true});


最大生存期参数[maxAge] 是一个方便的设置项来设置过期时间,值为相对于当前时间的毫秒时间。下面的代码就是这样的一个例子。

1 res.cookie('rememberme','1',{maxAge:900000,httpOnly:true});


当一个对象被序列化为JSON后是可以被设置为值的,并且它也会自动被bodyParser()中间件解析。

1 res.cookie('cart',{items:[1,2,3]});
2 res.cookie('cart',{items:[1,2,3]},{maxAge:900000});


被签名的cookie也同样被支持通过这种方法设置,简单的通过signed参数。当被给定的res.cookie()将会使用通过cookieParser(secret)传递进来的参数来签名。

1 res.cookie('name','tobi',{signed:true});


之后你就可以通过req.signedCookie对象来访问这个值。

res.clearCookie(name,[options])

清除名为 name 的cookie ,默认作用域为’/’

1 res.cookie('name','tobi',{path:'/admin'});
2 res.clearCookie('name',{path: '/admin'});


res.redirect([status],url)

重定向至给定的 url 并且支持指定 status 代码,默认为 302 方式

1 res.redirect('/foo/bar');

2 res.redirect('/http://example.com');
3 res.redirect(301,'http://example.com');
4 res.redirect('../login');


Express支持 一下几种重定向首先是通过全的符合规则的URL重定向到一个完全不同的域名。

1 res.redirect('http://google.com');


第二点是相对根域名重定向,例如,如果你想从http://example.com/admin/post/new 跳转至 /admin 下,你使用下面的代码,将会是你跳转到http://ehttp://example.com/admin

1 res.redirect('/admin');


第三点是相对于挂载点跳转,例如,如果你的博客程序挂载在’/blog’,而事实上,它是不知道自己被挂载在哪里的,此时你想重定向至’/admin/post/new’下,你将会被带到’http://example.com/admin/post/new’ 使用下面的代码,将会将页面重定向至’http://example.com/blog/admin/post/new’

1 res.redirect('admin/post/new');


当然也是允许页面路径相对跳转的。如果你现在在’http://example.com/admin/post/new’,使用下面的代码,你可以被带到’http://example.com/admin/post’

1 res.redirect('..');


最后还有一种特殊的跳转,即’back’重定向,它会将您重定向至 Referer (或者是Referrer),当来源不存在时默认定向至 ‘/’下。

1 res.redirect('back');


res.location

设置location响应头

1 res.location('/foo/bar');
2 res.location('/foo/bar');
3 res.location('http://example.com');
4 res.location('../login');
5 res.location('back');


可以使用与res.redirect()相同的urls

例如,如果你的程序被挂载在/blog 下面的代码将会将location响应头赋值为/blog/admin

1 res.location('admin');


 res.send([body|status],[body])

发送一个响应。

1 res.send(new Buffer('whoop'));
2 res.send({sond:'json'});
3 res.send('some html');
4 res.send(404,'Sorry, we cannot find that!');
5 res.send(500,{error:'something blew up'});
6 res.send(200);


在简单的non-streaming响应时,这个方法会自动进行一些有用的任务。例如如果之前没有定义过Content-Length,他会自动分配,它会自动设置一些HEAD信息,或者HTTP缓存支持。

当传入的内容为指定的Buffer,那么Content-Type会被设置为”application/octet-stream” 除非你预先执行了下面的定义。

1 res.set("Content-Type",'text/html');
2 res.send(new Buffer('some html'));


当一个数组或者是对象被传入Express将会自动转化为JSON的形式响应:

1 res.send({user:'tobi'});
2 res.send([1,2,3]);


最后,如果给定的参数是一个数字,而且没有上面提到的任何一个响应体,Express会为你设置一个默认的响应体。例如200 将会被设置响应体为 “OK” 和 404 将会被设置为”Not Found” 等。

1 res.send(200)
2 res.send(404)
3 res.send(500


res.json([status|body],[body])

发送一个JSON响应。这个方法与res.send()是完全相同的,当一个对象或者数组被传入的时候。然而它或许是有用的,例如在转化一些非对象(null,undefined,等等),因为这些并不是有效的JSON。

1 res.json(null)
2 res.json({user:'tobi'});
3 res.json(500,{error:'message'})


res.jsonp([status|body],[body])

发送一个支持JSONP的JSON响应。这个方法是和res.json()完全相同的,但是它支持JSONP callback

1 res.jsonp(null);
2 //=>null
3 res.jsonp({user:'tobi'});
4 //=>{"user": "tobi"}
5 res.jsonp(500,{error:'message'})
6 //=>{"error":"message"}


默认的JSONP回调函数名字是callback ,然而你可以通过jsonp callback name 设置项来设置,下面的代码是使用jsonp的一些例子。

1 // ?callback=foo
2 res.jsonp({user:'tobi'})
3 //=>foo({"user":"tobi"})
4 app.set('jsonp callback name','cb')
5
6 //?cb=foo
7 res.jsonp(500,{error:'message'});
8 //=>foo({"error":"message"});


res.type(type)

将内容的类型设置为MIME类型的 type ,可以是简写,也可以是存在’/’的字符串。当’/’存在时,类型就确定为type

1 res.type('.html');
2 res.type('html');
3 res.type('json');
4 res.type('application/json');
5 res.type('png');


res.format(object)

设置特定请求头的响应,这个方法是使用req.accepted,这个是一个根据其可接受类型的重要性排序的数组,否则,第一个回调函数将会被调用。当没有合适的匹配时,系统返回406 “NotAcceptable” 或者调用 default 回调函数。

Content-Type会被设置好在你被选择的回调函数执行的时候,然而你可以通过res.set()或者res.type()更改这里的类型。

下面的例子为在接受请求头字段被设置为”application/json”或者”*/json”的时候回返回{“message”:”hey”},然而,如果”*/*”时将会返回”hey”。

1 res.format({
2    'text/plain':function(){
3         res.send('hey');
4    },
5    'text/html':function(){
6         res.send('hey');
7    },
8    'application/json':function(){
9         res.send({message:"hey"});
10    }
11 });


除了使用一些标准的MIME类型,你也可以是用扩展名映射这些类型,下面是一些详细的展示。

1 res.format({
2    text:function(){
3        res.send('hey');
4    },
5    html:function(){
6        res.send('hey');
7    },
8    json:function(){
9        res.send({message:'hey'});
10    }
11 });


 res.attachment([filename])

设置响应头”Content-Disposition”的值为”attachment”。如果一个文件被给定,然后Content-Type将会被自动设置为基于其扩展名的的类型通过res.type(),然后Content-Disposition的”filename=”字段将会自动被设置。

 
1 res.attachment();
2 //Content-Disposition :attachment
3 res.attachment('path/to/logo.png');
4 //Content-Disposition : attachment;filename="logo.png"
5 //Content-Type: image/png


res.sendfile(path,[options],[fn])

path用来传递文件的路径。

通过文件的扩展名将会自动设置默认的Content-Type,然后回调函数 fn(err)将会被调用在传送后或者是产生任何错误的时候。

Options:

maxAge 以毫秒为单位,默认是0
root 相对于文件名的根目录
这种方法提供了细粒度的文件存储缩略图服务

1 app.get('/user/:uid/photo/:file',function(req,res){
2     var uid = req.params.uid,
3         file = req.params.file;
4     req.user.mayVierFilesFrom(uid,function(yes){
5         if(yes){
6             res.sendfile('/uploads/'+uid+'/'+file);
7         }else{
8             res.send(403,'Sorry! you cant see that.');
9         }
10      })
11 })


点击此处寻求更多的帮助,send

res.download(path,[filename],[fn])

path传输所需要传输的文件的路径,通常浏览器会提示用户下载。浏览器弹出的下载文件窗口的文件名和响应头里的Content-Disposition 的”filename=”参数是一致的。你也可以自己定义文件名。

当发生错误或者是一个文件传送完成将会调用回调函数 fn 。这个方法是用res.sendfile()来发送文件。

 
1 res.download('/report-12345.pdf');
2 res.download('/report-12345.pdf','report.pdf');
3 res.download('/report-12345.pdf','report.pdf',function(err){
4       if(err){
5            //处理错误,可能只有部分内容被传输,所以检查一下res.headerSent
6       }else{
7           //减少下载的积分值之类的。
8       }
9 });


 res.link(links)

合并并填充响应头内的”Link”字段,通过给定的links。

1 res.links({

2      next:'http://api.example.com/users?page=2',
3      last:'http://api.example.com/users?page=5'
4 });


处理后

1 Link: <http://api.example.com/users?page=2>; rel="next",
2       <http://api.example.com/users?page=5>; rel="last


 res.locals

一次请求的本地化变量,因此只能保持在一次请求/响应的view的输出之前,其实这个和API的app.locals是一样的。

这个对象是放置请求级的信息,此时放置请求的路径名,验证过的用户和用户设置等等。

1 app.use(function(req,res,next){
2     res.locals.user = req.user;
3     res.locals.authenticated = ! req.user.anonymous;
4     next();
5 });


res.render(view,[locals],callback)

渲染一个view,同时向callback传递渲染后的字符串,如果在渲染过程中有错误发生next(err)将会被自动调用。callback将会被传入一个可能发生的错误以及渲染后的页面,这样就不会自动输出了。

1 res.render('index',function(err,html){
2     //....
3 });
4 res.render('user',{name :'Tobi'},function(err,html){
5     //...
6 })


转自:http://www.90it.net/expressjs-4-api-zh-cn-response.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: