Node.js - 响应对象(Response Object)


res 对象表示 Express 应用程序在收到 HTTP 请求时发送的 HTTP 响应。

响应对象属性

以下是与响应对象关联的几个属性的列表。

属性 描述
res.app 此属性包含对使用中间件的 express 应用程序实例的引用。
res.headersSent 布尔属性,指示应用程序是否为响应发送了 HTTP 标头。
res.locals 一个对象,其中包含范围限定为请求的响应局部变量

响应对象方法

res.append(字段 [, 值])


res.append(field [, value])

该方法将指定的值附加到 HTTP 响应头字段。以下是一些示例 -


res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);
res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');
res.append('Warning', '199 Miscellaneous warning');

res.attachment([文件名])


res.attachment([filename])

此方法用于在 HTTP 响应中将文件作为附件发送。以下是一些示例 -


res.attachment('path/to/logo.png');

res.cookie(名称, 值 [, 选项])

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

该方法用于将 cookie name 设置为 value。value 参数可以是转换为 JSON 的字符串或对象。以下是一些示例 -


res.cookie('name', 'tobi', { domain: '.example.com', path: '/admin', secure: true });

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

res.clearCookie(名称 [, 选项])


res.clearCookie(name [, options])

该方法用于清除 name 指定的 Cookie。以下是一些示例 -


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

res.download(路径 [, 文件名] [, fn])


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

此方法用于将 path 处的文件作为 “附件” 传输。通常,浏览器会提示用户下载。以下是一些示例 -


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

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

res.download('/report-12345.pdf', 'report.pdf', function(err){

});

res.end([数据] [, 编码])


res.end([data] [, encoding])

该方法用于结束响应过程。以下是一些示例 -


res.end();

res.status(404).end();

res.format(对象)


res.format(object)

此方法用于对请求对象上的 Accept HTTP 标头(如果存在)执行内容协商。以下是一些示例 -


res.format ({
   'text/plain': function() {
      res.send('hey');
   },

   'text/html': function() {
      res.send('hey'); 
   },

   'application/json': function() {
      res.send({ 消息: 'hey' });
   },

   'default': function() {
      // 记录请求并用406进行响应
      res.status(406).send('Not Acceptable');
   }
});

res.get(字段)


res.get(field)

该方法用于返回 field 指定的 HTTP 响应头。下面是一个示例 -


res.get('Content-Type');

res.json([正文])


res.json([body])

此方法用于发送 JSON 响应。以下是一些示例 -


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

res.jsonp([正文])


res.jsonp([body])

此方法用于发送支持 JSONP 的 JSON 响应。以下是一些示例 -


res.jsonp(null)
res.jsonp({ user: 'tobi' })
res.status(500).jsonp({ error: 'message' })

res.links(链接)


res.links(links)

此方法用于联接作为参数属性提供的链接,以填充响应的 Link HTTP 标头字段。以下是一些示例 -


res.links ({
   next: 'http://api.example.com/users?page=2',
   last: 'http://api.example.com/users?page=5'
});

res.location(路径)


res.location(path)

该方法用于根据指定的 path 参数设置响应 Location HTTP header 字段。以下是一些示例 -


res.location('/foo/bar');
res.location('foo/bar');
res.location('http://example.com');

res.reRedirect([状态,] 路径)


res.redirect([status,] path)

该方法用于重定向到从指定路径提取的 URL,并指定 HTTP 状态码状态。以下是一些示例 -


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

res.render(视图 [, 局部变量] [, 回调])


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

此方法用于呈现视图并将呈现的 HTML 字符串发送到客户端。以下是一些示例 -


// 将渲染的视图发送到客户端
res.render('index');

// 将局部变量传递给视图
res.render('user', { name: 'Tobi' }, function(err, html) {
   // ...
});

res.send([正文])


res.send([body])

此方法用于发送 HTTP 响应。以下是一些示例 -


res.send(new Buffer('whoop'));
res.send({ some: 'json' });
res.send('<p>some html</p>');

res.sendFile(路径 [, 选项] [, fn])


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

此方法用于在给定路径处传输文件。根据文件名的扩展名设置 Content-Type 响应 HTTP 标头字段。下面是一个示例 -


res.sendFile(fileName, options, function (err) {
   // ...
});

res.sendStatus(状态代码)


res.sendStatus(statusCode)

该方法用于将响应 HTTP 状态码设置为 statusCode,并将其字符串表示形式作为响应体发送。以下是一些示例 -


res.sendStatus(200); // 相当于res.status(200).send(OK)
res.sendStatus(403); // 相当于res.status(403).send(“禁止”)
res.sendStatus(404); // 相当于res.status(404).send(“未找到”)
res.sendStatus(500); // 相当于res.status(500).send(“内部服务器错误”)

res.set(字段 [, 值])


res.set(field [, value])

此方法用于将响应的 HTTP 标头字段设置为 value。以下是一些示例 -


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

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

res.status(代码)


res.status(code)

此方法用于设置响应的 HTTP 状态。以下是一些示例 -


res.status(403).end();
res.status(400).send('Bad Request');
res.status(404).sendFile('/absolute/path/to/404.png');

res.type(类型)


res.type(type)

该方法用于将 Content-Type HTTP 头设置为 MIME 类型。以下是一些示例 -


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: