express框架响应对象res的方法

xiaoxiao2021-02-28  70

基本使用方法

var express = require('express') var app = express() app.get('/', [a, b], function(req, res, next), function(req, res))

Res对象的方法

res.download()

提示下载文件。

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

通过传递路径,把文件当作附件传递。一般而言,浏览器会提示用户下载消息。Content-Disposition头部’filename=’参数默认是路径(这点在日志中会有所显示)。可以通过传递一个参数值[, filename]来重写覆盖。

当错误发生或者转换结束,该方法会回调一个函数fn,然后这个方法会调用res.sendFile()来传递文件。

例子

res.download('/report-12345.pdf'); res.download('/report-12345.pdf', 'report.pdf') res.download('/report-12345.pdf', 'report.pdf', function(err) { if (err) { } else { } })

res.end()

终结响应处理流程。

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

来自Node核心,http.ServerResponse的response.end()方法,这个方法通常用来快速结束处理流程而且不带数据,但是如果你需要用数据响应,用res.send()或者res.json()替代。

例子

res.end() res.status(404).end()

res.json()

发送一个JSON格式的响应。

res.json([body])

发送一个JSON响应,这个方法与带有对象或者数组参数的res.send()方法是一样的,但是你可以在这个方法中传递一些其他值比如null或者undefined(即是这在JSON中也不是有效值)。

例子

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

res.jsonp()

发送一个支持JSONP的JSON格式的响应。

res.jsonp([body])

发送一个带有JSONP支持的JSON响应,这个方法与res.json()一样,除了它是通过JSONP回调支持。

例子

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

res.redirect()

重定向请求。

res.redirect([status,] path)

重定向到明确的路径,需要有明确的HTTP status代码,如果没有,默认status代码为 ‘302’ ‘Found’。

res.redirect('/foo/bar'); res.redirect('http://example.com'); res.redirect(301, 'http://example.com'); res.redirect('../login'); // 路径可以是另外一个站点的绝对路径 res.redirect('http://www.baidu.com'); // 路径可以与主机名相关,举个例子,如果应用放在'http://example.com/admin/post/new',下面这个路径会导向'http://example.com/admin' res.redirect('/admin'); // 路径可以与现在的路径相关,比如,在'http://example.com/blog/admin/', 下面这个会导向'http://example.com/blog/admin/post/new' res.redirect('post/new') // 如果你在'http://example.com/admin/post/new' res.redirect('..') res.redirect('back')

res.render()

渲染视图模板。

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

渲染一个视图,并把一个HTML字符串发送给客户端,locals是一个对象,其属性定义了视图内的局部变量。callback是一个回调函数,如果提供了,这个方法返回可能的错误信息和渲染字符串。如果有错误,这个方法会使用一个next(err)的内部函数。

PS:局部变量cache确保视图缓存,设置为true,在开发过程中缓存视图,这样视图在生产过程中默认可用。

// 发送view到客户端 res.render('index'); // 如果回调被定义,渲染的HTML字符串需要被明确发送 res.render('index', function(err, html) { res.send(html) }) // 传递一个本地变量给视图 res.render('user', { name: 'Tobi' }, function(err, html) { })

res.send()

发送各种类型的响应。

res.send([body])

body对象可以是一个缓冲区对象,一个字符串,一个单纯的对象或者数组。

例子

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

这个方法自动提供HTTP响应头,比如如果body对象是个buffer对象,这个方法自动把’Content-Type’设置为’application/octet-stream’,除非已预定义了。

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

res.sendFile

以八位字节流的形式发送文件。

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

通过给定的路径传递文件,通过文件的扩展名设置响应头Content-Type。除非root选项已经在参数options中设置了,path必须是绝对路径。

关于options

PropertyDescriptionDefaultAvailabilitymaxAgeSets the max-age property of the Cache-Control header in milliseconds or a string in ms format0 rootRoot directory for relative filenames.  lastModifiedSets the Last-Modified header to the last modified date of the file on the OS. Set false to disable it.Enabled4.9.0+headersObject containing HTTP headers to serve with the file.  dotfilesOption for serving dotfiles. Possible values are “allow”, “deny”, “ignore”.“ignore” 

例子

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.sendStatus()

设置响应状态代码,并将其以字符串形式作为响应体的一部分发送。

res.sendStatus(statusCode)

设置响应HTTP状态码为statusCode。

res.sendStatus(200); // equivalent to res.status(200).send('OK') res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') res.sendStatus(404); // equivalent to res.status(404).send('Not Found') res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
转载请注明原文地址: https://www.6miu.com/read-53844.html

最新回复(0)