博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
了解Express.js中的res对象
阅读量:2510 次
发布时间:2019-05-11

本文共 5734 字,大约阅读时间需要 19 分钟。

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

Nice to Eat Ya!

') res.send('*Splish Splash*')});

Express.js will automatically append Content-Type and Content-Length headers for the response. Pretty nifty!

Express.js将自动为响应添加Content-TypeContent-Length标头。 很漂亮!

res.status (res.status)

Specify the HTTP status code for the response:

指定响应的HTTP状态代码:

res.status(404).send('Not Found');// alternatively...res.sendStatus(404);

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代码执行各种操作,例如显示“未找到”页面,或者知道是否应缓存图像。

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 , , or you can make data available to your templates. In the above example {status: 'not-dead'} is available as res.locals.status.

如果要构建服务器呈现的网站,则此方法将发送客户端HTML页面。 如果将此方法与模板语言(例如 , 或结合使用,则可以使数据可用于模板。 在上面的示例中, {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() ,它将自动结束响应。

发送文件 (Sending Files)

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.jpgapp.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.jpgapp.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)

Headers in HTTP are like the sticker that FedEx puts on boxes. These stickers detail various characteristics about your package:

HTTP中的标头就像FedEx放在盒子上的标签一样。 这些贴纸详细说明了您包裹的各种特征:

  • Recipient

    接受者
  • Address to release the package

    释放包裹的地址
  • Total weight of package

    包装总重量
  • Hazardous material handling

    危险品处理
  • Whether to require a signature

    是否要求签名

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. 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,并且由于标签遵循某些规格,因此他们将知道如何运送包裹。 非常相似! 它们是遵循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标头。 可能是您的回复中最重要的标题之一。

结论 (Conclusion)

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 website.

你有它! 这些是在Express.js中使用res滚动所需的全部基本知识。 要获取有关res全面信息,请访问网站。

翻译自:

转载地址:http://sshgb.baihongyu.com/

你可能感兴趣的文章
iOS开发中遇到的问题整理 (一)
查看>>
Linux(SUSE 12)安装jboss4并实现远程访问
查看>>
Neutron在给虚拟机分配网络时,底层是如何实现的?
查看>>
netfilter/iptables全攻略
查看>>
Overlay之VXLAN架构
查看>>
Eclipse : An error occurred while filtering resources(Maven错误提示)
查看>>
在eclipse上用tomcat部署项目404解决方案
查看>>
web.xml 配置中classpath: 与classpath*:的区别
查看>>
suse如何修改ssh端口为2222?
查看>>
详细理解“>/dev/null 2>&1”
查看>>
suse如何创建定时任务?
查看>>
suse搭建ftp服务器方法
查看>>
centos虚拟机设置共享文件夹并通过我的电脑访问[增加smbd端口修改]
查看>>
文件拷贝(IFileOperation::CopyItem)
查看>>
MapReduce的 Speculative Execution机制
查看>>
大数据学习之路------借助HDP SANDBOX开始学习
查看>>
Hadoop基础学习:基于Hortonworks HDP
查看>>
为什么linux安装程序 都要放到/usr/local目录下
查看>>
Hive安装前扫盲之Derby和Metastore
查看>>
永久修改PATH环境变量的几种办法
查看>>