欢迎您访问DoraCMS 您可以登录 或注册
  • 微信客服:476847113微信客服
  • 微信公众号微信公众号
您现在的位置是:首页 > Express

Express 4.8.x—Response 响应对象

doramart2015-10-17 13:17:37
由于API很简单,以下内容基本上是Express官网API的中文翻译,特殊的地方会做解释说明。

Response  响应对象

由于API很简单,以下内容基本上是Express官网API的中文翻译,特殊的地方会做解释说明。

res.status(code)

设置http响应码,比如 res.status(404)

res.set(field, [value])

设置响应头信息。 有两种写法:

res.set('Content-Type', 'text/plain');

和json写法:

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

它的别名是 `res.header(field, [value])`

res.get(field)

得到响应头信息

设置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 属性是一个便利的设置"expires",它是一个从当前时间算起的毫秒。 下面的代码和上一个例子中的第二行是同样的作用。

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

这个方法也支持签名的cookies。 只需要简单的传递signed 参数。 res.cookie()会使用通过 express.cookieParser(secret) 传入的secret来签名这个值

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

res.clearCookie

把name的cookie清除. path参数默认为 "/". res.cookie('name', 'tobi', { path: '/admin' }); res.clearCookie('name', { path: '/admin' });

res.redirect([status], url)

使用可选的状态码跳转到url 状态码status默认为302 "Found".

res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');

Express支持几种跳转,第一种便是使用一个完整的URI跳转到一个完全不同的网站。

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

第二种是相对根域路径跳转,比如你现在在 http://example.com/admin/post/new, 下面的代码跳转到 /admin 将会把你带到http://example.com/admin:

res.redirect('/admin');

这是一种相对于应用程序挂载点的跳转。 比如把一个blog程序挂在 /blog, 事实上它无法知道它被挂载,所以当你使用跳转 /admin/post/new 时,将跳到http://example.com/admin/post/new, 下面的代码,会把你带到http://example.com/blog/admin/post/new

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

googog路径名.跳转同样也是支持的。 比如你在http://example.com/admin/post/new, 下面的跳转会把你带到 http//example.com/admin/post:

res.redirect('..');

最后也是最特别的跳转是 back 跳转, 它会把你带回Referer(也有可能是Referrer)的地址 当Referer丢失的时候默认为 /

res.redirect('back');

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

res.charset

设置字符集。默认为"utf-8"。

res.charset = 'value';
res.send('some html');
// => Content-Type: text/html; charset=value

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

发送一个响应。

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

这个方法在输出non-streaming响应的时候自动完成了大量有用的任务 ,比如在它前面没有定义Content-Length, 它会自动设置; 比如加一些自动的 HEAD; 比如对HTTP缓存的支持 . 当参数为一个 Buffer时 Content-Type 会被设置为 "application/octet-stream" 除非它之前有像下面的代码:

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

当参数为一个String时 Content-Type 默认设置为"text/html":

res.send('some html');

当参数为 Array 或者 Object 时 Express 会返回一个 JSON :

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

最后一条当一个Number 作为参数, 并且没有上面提到的任何一条在响应体里, Express会帮你设置一个响应体,比如200 会返回字符"OK", 404会返回"Not Found"等等.

res.send(200)
res.send(204)
res.send(500)

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

返回一个 JSON 响应。 当res.send() 的参数是一个对象或者数组的时候, 会调用这个方法。 当然它也在复杂的空值(null, undefined, etc)JSON转换的时候很有用, 因为规范上这些对象不是合法的JSON。

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

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

返回一个支持JSONP的JSON响应。 Send a JSON response with JSONP support. 这个方法同样使用了res.json(), 只是加了一个可以自定义的 JSONP 回调支持。

res.jsonp(null)
// => null

res.jsonp({ user: 'tobi' })
// => { "user": "tobi" }

res.jsonp(500, { error: 'message' })
// => { "error": "message" }

默认情况下JSONP 回调的函数名就是callback。 你可以通过jsonp callback name来修改这个值。 下面是一些使用JSONP的例子。

// ?callback=foo
res.jsonp({ user: 'tobi' })
// => foo({ "user": "tobi" })

app.set('jsonp callback name', 'cb');

// ?cb=foo
res.jsonp(500, { error: 'message' })
// => foo({ "error": "message" })

res.type(type)

设置响应内容类型,也就是响应头的Content-Type值,而这个方法无需我们写全,即可被成功设置,意思是res.type(“json”),等价于 res.type('application/json')。

res.type('.html');
res.type('html');
res.type('json');
res.type('application/json');
res.type('png');

它是res.contentType(type)方法的别名。

res.format(object)

设置特定请求头的响应。 这个方法使用 req.accepted, 这是一个通过质量值作为优先级顺序的数组, 第一个回调会被执行。 当没有匹配时,服务器返回一个 406 "Not Acceptable", 或者执行default 回调 Content-Type 在callback 被选中执行的时候会被设置好, 如果你想改变它,可以在callback内使用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' });
  }
});

res.attachment([filename])

设置响应头的Content-Disposition 字段值为 "attachment". 如果有filename 参数,Content-Type 将会依据文件扩展名通过res.type()自动设置, 并且Content-Disposition的"filename="参数将会被设置

res.attachment();
// Content-Disposition: attachment

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

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

path所传输附件的路径。 它会根据文件的扩展名自动设置响应头里的Content-Type字段。 回调函数fn(err)在传输完成或者发生错误时会被调用执行。 Options:

  • maxAge 毫秒,默认为0

  • root 文件相对的路径 这个方法可以非常良好的支持有缩略图的文件服务。

    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.send(403, 'Sorry! you cant see that.');
      }
    });
    });

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

    path所需传输附件的路径, 通常情况下浏览器会弹出一个下载文件的窗口。 浏览器弹出框里的文件名和响应头里的Disposition "filename=" 参数是一致的, 你也可以通过传入filename来自由设置。 当在传输的过程中发生一个错误时,可选的回调函数fn会被调用执行。 这个方法使用res.sendfile()传输文件。

    res.download('/report-12345.pdf');

    sex```

res.download('/report-12345.pdf', 'report.pdf');

```

res.download('/report-12345.pdf', 'report.pdf', function(err){
  if (err) {
    // 处理错误,请牢记可能只有部分内容被传输,所以
    // 检查一下res.headerSent
  } else {
    // 减少下载的积分值之类的
  }
});

合并给定的links, 并且设置给响应头里的"Link" 字段.

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"

res.locals

在某一次请求范围下的响应体的本地变量,只对此次请求期间的views可见。 另外这个API其实和 app.locals是一样的. 这个对象在放置请求级信息时非常有用,比如放置请求的路径名,验证过的用户,用户设置等等

app.use(function(req, res, next){
  res.locals.user = req.user;
  res.locals.authenticated = ! req.user.anonymous;
  next();
});

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

渲染view, 同时向callback 传入渲染后的字符串。 callback如果不传的话,直接会把渲染后的字符串输出至请求方, 如果不需要再对渲染后的模板作操作,就不用传callback。 当有错误发生时next(err)会被执行. 如果提供了callback参数,可能发生的错误和渲染的字符串都会被当作参数传入, 并且没有默认响应。

res.render('index', function(err, html){
  // ...
});

res.render('user', { name: 'Tobi' }, function(err, html){
  // ...
});

所有文章未经授权禁止转载、摘编、复制或建立镜像,违规转载法律必究。

举报邮箱:doramart@qq.com

相关标签: express
取消回复
登录 参与评论

评论列表(