express学习_4.express响应对象

1:什么是响应对象
    响应对象是指服务端向客户端响应数据的对象,包含了所有要响应的数据。

2:响应对象的方法
    
    a: res.send(data)方法    //响应任意数据
        注意:
        如果响应一个数字,会被当成是状态吗,很容易出现错误,需要将数字加引号转为字符串发送。
        send方法只能出现一次,不能重复,重复无效,而且报错。
        可链式使用,如:res.state(404).send('<h1>404</h1>');

    b: res.json({data})方法    //自动设置响应头

    c: res.render()方法    //渲染模板
        res.render('模板名称', {数据});    //读取模板文件,拼接数据,自动将结果发送到浏览器

    d: res.redirect()方法    //服务器端重定向跳转
        res.redirect('http://www.baidu.com');
    
    其他API

    1): res.status(code) //设置状态码
    支持连贯调用
    如:res.status(404).sendfile('path/to/404.png');
    
    2): res.set(field,[value])
    设置请求头的字段为指定的值,或者通过一个对象一次设置多个值。

    如:res.set('Content-Type','text/plain');
    如:res.set({
           'Content-Type':'text/plain',
           'Content-Length':'123',
           'ETag':'12345'
        });

    3): res.get(field)
    获取不区分大小写的响应头 “field”(字段)。
    如:res.get('Content-Type');    //=>"text/plain"

    4): res.cookie(name,value,[options])
    设置cookie name 的值为 value,接受参数可以一个字符串或者是对象转化成的JSON,path 默认设置为’/’。
    如:res.cookie('name','tobi',{domain:'.example.com',path:'/admin',secure:true});
    如:res.cookie('rememberme','1',{expires:new Date(Date.now() + 900000),httpOnly:true});
    最大生存期参数[maxAge] 是一个方便的设置项来设置过期时间,值为相对于当前时间的毫秒时间。下面的代码就是这样的一个例子。 
    如:res.cookie('rememberme','1',{maxAge:900000,httpOnly:true});
    当一个对象被序列化为JSON后是可以被设置为值的,并且它也会自动被bodyParser()中间件解析。
    如:res.cookie('cart',{items:[1,2,3]});
    如:res.cookie('cart',{items:[1,2,3]},{maxAge:900000});
    被签名的cookie也同样被支持通过这种方法设置,简单的通过signed参数。当被给定的res.cookie()将会使用通过cookieParser(secret)传递进来的参数来签名。
    如:res.cookie('name','tobi',{signed:true});

    5): res.clearCookie(name,[options])
    清除名为 name 的cookie ,默认作用域为’/’
    如:res.cookie('name','tobi',{path:'/admin'});
    如:res.clearCookie('name',{path: '/admin'});

    6): res.location
    设置location响应头
    如:res.location('/foo/bar');
    如:res.location('/foo/bar');
    如:res.location('http://example.com');
    如:res.location('../login');
    如:res.location('back');
    可以使用与res.redirect()相同的urls
    例如,如果你的程序被挂载在/blog 下面的代码将会将location响应头赋值为/blog/admin
    如:res.location('admin');

    7): res.jsonp([status|body],[body])
    发送一个支持JSONP的JSON响应。这个方法是和res.json()完全相同的,但是它支持JSONP callback
    如:res.jsonp(null);    //=>null
    如:res.jsonp({user:'tobi'});    //=>{"user": "tobi"}
    如:res.jsonp(500,{error:'message'})    //=>{"error":"message"}
    默认的JSONP回调函数名字是callback ,然而你可以通过jsonp callback name 设置项来设置,下面的代码是使用jsonp的一些例子。
    如:res.jsonp({user:'tobi'})    //=>foo({"user":"tobi"})
    如:app.set('jsonp callback name','cb')    //cb=foo
    如:res.jsonp(500,{error:'message'});    //=>foo({"error":"message"});

    8): res.type(type)
    将内容的类型设置为MIME类型的 type ,可以是简写,也可以是存在’/’的字符串。当’/’存在时,类型就确定为type
    如:res.type('.html');
    如:res.type('html');
    如:res.type('json');
    如:res.type('application/json');
    如:res.type('png');

    9): res.format(object)
    设置特定请求头的响应,这个方法是使用req.accepted,这个是一个根据其可接受类型的重要性排序的数组,否则,第一个回调函数将会被调用。
    当没有合适的匹配时,系统返回406 “NotAcceptable” 或者调用 default 回调函数。
    Content-Type会被设置好在你被选择的回调函数执行的时候,然而你可以通过res.set()或者res.type()更改这里的类型。
    下面的例子为在接受请求头字段被设置为”application/json”或者”*/json”的时候回返回{“message”:”hey”},然而,如果”*/*”时将会返回”hey”。
    res.format({
       'text/plain':function(){
            res.send('hey');
       },
       'text/html':function(){
            res.send('hey');
       },
       'application/json':function(){
         res.send({message:"hey"});
       }
     });
    除了使用一些标准的MIME类型,你也可以是用扩展名映射这些类型,下面是一些详细的展示。
    res.format({
       text:function(){
           res.send('hey');
       },
       html:function(){
           res.send('hey');
       },
       json:function(){
           res.send({message:'hey'});
       }
     });

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

    11): res.sendfile(path,[options],[fn])
    path用来传递文件的路径。
    通过文件的扩展名将会自动设置默认的Content-Type,然后回调函数 fn(err)将会被调用在传送后或者是产生任何错误的时候。
    Options:
        maxAge 以毫秒为单位,默认是0
        root 相对于文件名的根目录
    这种方法提供了细粒度的文件存储缩略图服务
    app.get('/user/:uid/photo/:file',function(req,res){
        var uid = req.params.uid,
             file = req.params.file;
        req.user.mayVierFilesFrom(uid,function(yes){
            if(yes){
                res.sendfile('/uploads/'+uid+'/'+file);
            }else{
                res.send(403,'Sorry! you cant see that.');
            }
          })
     })

    12): res.download(path,[filename],[fn])
    path传输所需要传输的文件的路径,通常浏览器会提示用户下载。
    浏览器弹出的下载文件窗口的文件名和响应头里的Content-Disposition 的”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){
              if(err){
                   //处理错误,可能只有部分内容被传输,所以检查一下res.headerSent
              }else{
                  //减少下载的积分值之类的。
              }
        });

    13): res.link(links)
    合并并填充响应头内的”Link”字段,通过给定的links。
    如:
    res.links({
         next:'http://api.example.com/users?page=2',
          last:'http://api.example.com/users?page=5'
    });
    处理后
    Link: <http://api.example.com/users?page=2>; rel="next",
           <http://api.example.com/users?page=5>; rel="last"

    14): res.locals
    一次请求的本地化变量,因此只能保持在一次请求/响应的view的输出之前,其实这个和API的app.locals是一样的。
    这个对象是放置请求级的信息,此时放置请求的路径名,验证过的用户和用户设置等等。
    如:
    app.use(function(req,res,next){
        res.locals.user = req.user;
        res.locals.authenticated = ! req.user.anonymous;
        next();
     });

    15): res.render(view,[locals],callback)
    渲染一个view,同时向callback传递渲染后的字符串,如果在渲染过程中有错误发生next(err)将会被自动调用。
    callback将会被传入一个可能发生的错误以及渲染后的页面,这样就不会自动输出了。
    如:
    res.render('index',function(err,html){
        //....
    });
    res.render('user',{name :'Tobi'},function(err,html){
        //...
    })


 

猜你喜欢

转载自blog.csdn.net/m0_37649018/article/details/82150438