The res
object in Express.js, short for response, gives you a simple interface to respond to HTTP requests. In this article, we’ll cover the most important parts of res
.
Express.js中的res
对象(是response的缩写)为您提供了一个简单的接口来响应HTTP请求。 在本文中,我们将介绍res
的最重要部分。
Check-out this sister post if you’re interested in the req
counterpart for access to information about the request.
如果您对req
对方感兴趣,请查看此姐妹帖子 ,以获取有关该请求的信息。
res
基础 (Basics of res
)res.send
(res.send
)send
is perhaps the most well-known method that’s used on res
. With res.send()
you can respond to HTTP requests with all sorts of data:
send
可能是用于res
的最著名的方法。 使用res.send()
您可以使用各种数据来响应HTTP请求:
app.get('/home', (req, res) => {
res.send(Buffer.from('greensnapper'))
res.send({ crocodiles: ['judy', 'nigel', 'spence'] }) // will convert to a string with JSON.stringify
res.send('<p>Nice to Eat Ya!</p>')
res.send('*Splish Splash*')
});
Express.js will automatically append Content-Type
and Content-Length
headers for the response. Pretty nifty!
Express.js将自动为响应添加Content-Type
和Content-Length
标头。 很漂亮!
res.status
(res.status
)Specify the HTTP status code for the response:
指定响应的HTTP状态代码:
res.status(404).send('Not Found');
// alternatively...
res.sendStatus(404);
HTTP status codes are the quickest way to summarize a server’s response. Browsers rely on HTTP codes for various things like displaying “Not Found” pages, or knowing whether an image should be cached.
HTTP状态代码是总结服务器响应的最快方法。 浏览器依靠HTTP代码执行各种操作,例如显示“未找到”页面,或者知道是否应缓存图像。
res.redirect
(res.redirect
)res.redirect('/crocodile/local-wetlands')
res.redirect('https://crocs.com')
You can redirect clients to local routes in your app, or to completely different websites.
您可以将客户端重定向到应用程序中的本地路由,或重定向到完全不同的网站。
res.render
(res.render
)app.get('/frogger-game', (req, res) => {
res.render('frogger.html', {status: 'not-dead'});
});
If you’re building server-rendered websites, this method will send the client HTML pages. If you combine this with a templating language like Pug, Mustache, or EJS you can make data available to your templates. In the above example {status: 'not-dead'}
is available as res.locals.status
.
如果要构建服务器呈现的网站,则此方法将发送客户端HTML页面。 如果将此方法与模板语言(例如Pug , Mustache或EJS)结合使用,则可以使数据可用于模板。 在上面的示例中, {status: 'not-dead'}
可作为res.locals.status
。
res.end
(res.end
)res.end();
res.send();
res.status(404).end();
Use this method to end the response to the client. Sometimes you will want to use this, but generally if you’re using res.send()
it will automatically end the response.
使用此方法可以结束对客户端的响应。 有时您会想要使用它,但是通常如果您使用res.send()
,它将自动结束响应。
Express.js doesn’t just give you simple utilities for sending JSON data and HTML files. You can also send files with res.sendFile()
:
Express.js不仅为您提供了用于发送JSON数据和HTML文件的简单实用程序。 您也可以使用res.sendFile()
发送文件:
res.sendFile
(res.sendFile
)// GET https://swamps.com/gallery/my-crib.jpg
app.get('/gallery/:fileName', function (req, res, next) {
var options = {
root: path.join(__dirname, 'public')
};
res.sendFile(req.params.fileName, options, function (err) {
if (err) next(err);
else console.log('Sent:', fileName);
});
});
The image located at https://swamps.com/public/my-crib.jpg
will be sent, and prompt the user’s browser to download the image. Simple huh? This isn’t something you’d want to tackle using the low-level http
module in Node.js!
位于https://swamps.com/public/my-crib.jpg
的图像将被发送,并提示用户的浏览器下载该图像。 简单吧? 使用Node.js中的低级http
模块不是您要解决的问题!
A note about the options
object. You need to set the “root” or you’ll need to provide an absolute path to your file.
关于options
对象的注释。 您需要设置“ root”,或者需要提供文件的绝对路径。
res.download
(res.download
)An alternative way to send a file is to use res.download
, which is more concise:
发送文件的另一种方法是使用res.download
,这更加简洁:
// GET https://swamps.com/gallery/my-crib.jpg
app.get('/gallery/:fileName', function(req, res){
const file = `${__dirname}/public/${req.params.fileName}`;
res.download(file);
});
It actually uses res.sendFile
under-the-hood so it performs the same actions like prompting the user’s browsers to download the file, as well as setting the appropriate headers (eg., Content-Type: image/jpeg
).
它实际上在res.sendFile
使用res.sendFile
,因此它执行相同的操作,例如提示用户的浏览器下载文件以及设置适当的标头(例如Content-Type: image/jpeg
)。
Headers in HTTP are like the sticker that FedEx puts on boxes. These stickers detail various characteristics about your package:
HTTP中的标头就像FedEx放在盒子上的标签一样。 这些贴纸详细说明了您包裹的各种特征:
Any FedEx driver can hand-off your package to UPS or USPS, and since the sticker follows certain specifications they’ll know how to deliver your package. HTTP Headers are quite similar! They’re metadata that follows W3C guidelines so servers and clients can communicate with each other in seamless harmony.
任何FedEx驾驶员都可以将包裹交给UPS或USPS,并且由于标签遵循某些规格,因此他们将知道如何运送包裹。 HTTP标头非常相似! 它们是遵循W3C准则的元数据,因此服务器和客户端可以无缝协调地相互通信。
res.append
(res.append
)res.append('Content-Type', 'application/javascript; charset=UTF-8');
res.append('Connection', 'keep-alive')
res.append('Set-Cookie', 'divehours=fornightly')
res.append('Content-Length', '5089990');
Use this to define any standard/non-standard headers in server responses.
使用它来定义服务器响应中的任何标准/非标准头。
res.type
(res.type
)res.type('png') // => 'image/png'
res.type('html') // => 'text/html'
res.type('application/json') // =>'application/json'
This is specifically for defining the Content-Type
header. Perhaps one of the most important headers to include in your responses.
这专门用于定义Content-Type
标头。 可能是您的回复中最重要的标题之一。
There you have it! These are the all the basics you need to know to get rollin’ with res
in Express.js. To get comprehensive information about res
visit the Express.js official documentation website.
你有它! 这些是在Express.js中使用res
滚动所需的全部基本知识。 要获取有关res
全面信息,请访问Express.js官方文档网站。
翻译自: https://www.digitalocean.com/community/tutorials/nodejs-res-object-in-expressjs