response入门

response

response对象表示对程序发出的http请求的响应。

response对象常用属性和方法

res.app()

该属性是express application一个引用实例,可以做为中件间使用。如下创建一个中间件模块,可在main文件中请求到该中间件函数。

--view.js

var app = require('express')();
module.exports = function (req, res) {
res.app.set('title', 'haha');
res.send('this tiltle is ' + res.app.get('title'));
}

-- main.js

var app = require('express')();
app.get("/view", require("./view.js"));
app.listen(3000);

res.headersSent

返回布尔型,查看是否发送HTTP响应头信息。

app.get('/', function (req, res) {
    console.log(res.headersSent); // false
    res.send('OK');
    console.log(res.headersSent); // true
})

res.send()

发送HTTP响应

res.send('Hello World!');

也可以结合res.status()使用,设置状态码并发送内容,两属性顺序更换后,res.status设置效果失效(不会报错)

res.status('500').send('Hello World!'); 
//两属性顺序更换后,res.status设置效果失效,代码等效于下面两行
res.send('Hello World!');
res.status('500') //响应已发送,再设置无效

res.set(field [, value])

设置HTTP响应头中的属性值。可使用一个对象设置多个参数。

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

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

res.get

返回文档中设定的响应头内容,参数不分大小写。

res.get('Content-type');

res.status(code)

设置HTTP响应状态码。

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

res.sendStatus()

设置响应头中的状态码,并将状态码的字符串表示作为响应正文内容

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

如果设置的状态码不被浏览器支持时,则是以下情况

res.sendStatus(2000); // equivalent to res.status(2000).send('2000')

res.redirect(path)

url重定向

1.指向另一个网页

res.redirect('http://www.xxt.cn');
res.redirect(301,'http://www.xxt.cn'); // 状态码也可为302,303等代码重定向的状态码;若为其他,则会以链接的形式显示

2.相同域名、端口号下的其他地址

res.redirect('/view');// 原path变为重定向内容,如locallhost:3000/go变为locallhost:3000/view;


res.redirect('view');// 原path中的最后一级变更为重定向内容,如http://locallhost:3000/go/to变为http://locallhost:3000/go/view;

3.返回path为“/”的地址

res.redirect('back');
res.redirect('..'); // 不同于接口手册中locallhost:3000/go/to变为locallhost:3000/go,而是与back一致

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

渲染视图,并将渲染的HTML呈现给用户。(callback 用来处理返回的渲染后的字符串,如果有callback,则需在回调函数内处理返回结果,callback函数体为空时,页面出现一直加载)

res.render('index'); // 显示该页面内容

res.render('index', function(err, html) {
    res.send(html); // 以回调函数的形式显示,可以通过判断err状态决定显示内容;
})

res.render('index', {
        supplies: ['hehe','haha','lala'],
        sayHello:function(name){
            return "Hello" + name;
        }
    },function(err, html) {
        res.send(html);
    }
)

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

设置cookie值,该值可以是字符串或JSON对象,options有以下属性:
<table>
<tr>
<td>属性</td><td>类型</td><td>描述</td>
</tr>
<tr>
<td>domain</td><td> String</td><td>Domain name for the cookie. Defaults to the domain name of the app. </td>
</tr>
<tr>
<td>encode</td><td> Function</td><td>A synchronous function used for cookie value encoding. Defaults to encodeURIComponent.</td>
</tr>
<tr>
<td>expiress</td><td> Date</td><td>Expiry date of the cookie in GMT. If not specified or set to 0, creates a session cookie.</td>
</tr>
<tr>
<td>httpOnly</td><td> Boolean</td><td> Flags the cookie to be accessible only by the web server.</td>
</tr>
<tr>
<td>maxAge</td><td> String</td><td>Convenient option for setting the expiry time relative to the current time in milliseconds.</td>
</tr>
<tr>
<td>path</td><td> String</td><td>Path for the cookie. Defaults to “/”.</td>
</tr>
<tr>
<td>secure</td><td> Boolean</td><td>Marks the cookie to be used with HTTPS only.</td>
</tr>
<tr>
<td>signed</td><td> Boolean</td><td>Indicates if the cookie should be signed. </td>
</tr>
</table>

app.get('/go', function(req, res) {
// 设置cookie
res.cookie('testCookie', {items:['7','9','11']});

// 读取cookie
var Cookies = {};
req.headers.cookie && req.headers.cookie.split(';').forEach(function( Cookie ) {
    var parts = Cookie.split('=');
    Cookies[ parts[ 0 ].trim() ] = ( parts[ 1 ] || '' ).trim();
});
console.log(Cookies);

res.end('Success!');
});

res.clearCookie(name[, options])

清除cookie,此处的options与res.cookie中的options属性内容一致。且当清除有条件限制的cookie时,清除语句中必须含有相应条件才行。

// 设置cookie

res.cookie('name', 'Json');
res.cookie('testCookie', '7', {path:'/admain'});

// 清除cookie

res.clearCookie('name');
res.clearCookie('testCookie', {path:'/admin'}); // 当无path条件限制时,该cookie无法清除

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

传输文件。通常使用时,浏览器会给用户提示下载信息。当文档下载出错或完成时,回调函数会被调用。

app.use('/:name', function(req, res) {
    var fileName = req.params.name;
    res.download(fileName, function(err) {
    if (err) {
        console.log('fail');
    } else {
        console.log('success');
    }
    });
});

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

根据路径传输文档,当条件中未设置存在文件的文档目录时,path要写成绝对路径。此外HTTP响应头中的Content-Type根据文档后缀来设置。options的属性内容如下:
<table>
<tr>
<td>Property</td><td>Description</td>
</tr>
<tr>
<td>maxAge</td><td> Sets the max-age property of the Cache-Control header in milliseconds or a string in ms format</td>
</tr>
<tr>
<td>root</td><td> Root directory for relative filenames.</td>
</tr>
<tr>
<td>lastModified</td><td> Sets the Last-Modified header to the last modified date of the file on the OS. Set false to disable it.</td>
</tr>
<tr>
<td>headers</td><td> Object containing HTTP headers to serve with the file.</td>
</tr>
<tr>
<td>dotfiles</td><td> Option for serving dotfiles. Possible values are “allow”, “deny”, “ignore”. </td>
</tr>
</table>

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

[注]path必须是绝对路径,且传输文档的名称后缀也必不可少。(绝对路径时注意''要转译'\')

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.set()在res.append()之后调用时,HTTP响应头中的值被重置。

res.attachment([filename])

【attachment:附件】
设置HTTP响应头中Content-Disposition为attachment。当给存在filename时,将会通过res.type()设置Content-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.format(object)

根据req.appcepts()请求内容,对响应内容进行格式化。

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

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

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

    'default': function() {
    // log the request and respond with 406
    res.status(406).send('Not Acceptable');
    }
});

也可以根据文档后缀名作为判断条件。

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

    html: function() {
    res.send('<p>hey</p>');
    },

    json: function() {
    res.send({ message: 'hey' });
    }
});

res.location(path)

设置HTTP响应头中的Location为指定路径参数。

res.location('/foo/bar');
res.location('http://example.com');
res.location('back'); // `back`有特殊含义,当referer无特定值时,Location将为`/`,否则为特定值

res.type(type)

设置HTTP头中的Content-Type为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:

res.vary(field)

在响应头中添加字段。

res.vary('User-Agent').render('docs');
res.vary('User-Agent').render('docs'); // 重复添加时,控制台报错

res.links(links)

在HTTP响应头的Link中添加属性参数。

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

res.locals

一个局限于请求包含响应局部变量的对象,其应用只会存在于请求/响应的周期中。否则将和app.locals等同。
这个属性通常用于列出请求层信息,如请求路径名称及user验证、设置等,也可在EJS中调用。

// express.js
app.get('/', function(req, res) {
res.locals.user = "Hello!";
res.render('index');
})


// index.ejs中调用语句
<body>
<%= user %>
</body>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,701评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,649评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,037评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,994评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,018评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,796评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,481评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,370评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,868评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,014评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,153评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,832评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,494评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,039评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,437评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,131评论 2 356

推荐阅读更多精彩内容