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>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容