res.send和res.sendFile

res.sendFile(path,[,options][,fn])  只支持express4.8.0之前的版本

通过给定的路径path读取文件,它会根据文件的扩展名设置HTTP的header中的Context-Type属性.

path必须是一个完整的路径.,除非你在options里面设置了root对象.例如

res.sendFile('index.html',{root:__dirname});

options条目

maxAge:  设置 header中 的max-age属性,单位是毫秒,默认是0(这是啥??)

root:  相关文件名的根目录

lastModified:  这个属性标记文件在服务器端最后被修改的时间具体看这里,,默认是false

headers: 包含HTTP的headers

dotfiles:  这个不知道是,但是感觉没啥用,可选值时allow,deny,ignore.默认是ignore

当文件传输完毕或者出错时,它会请求一个回调函数fn(err),回调函数必须对响应做出一个明确的处理:结束或者传递到下一个路由

这是一个包含所有可选项的例子:

app.get('/file/:name', function (req, res, next) {

  var options = {
    root: __dirname + '/public/',
    dotfiles: '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('/uploads/' + uid + '/' + file);
    } else {
      res.status(403).send('Sorry! you cant see that.');
    }
  });});

res.send:发送一些HTTP响应,这个感觉能说的不多,这里写一下它send的内容参数

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' });


转载于:https://my.oschina.net/boogoogle/blog/597127

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值