Node.js后端开发 - 进阶篇 #7 express框架之res对象的常见方法

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/YuDBL/article/details/102540869

目录

一、前言

二、浏览中文官网API

三、res(response)对象的一些常见方法

1、res.json([body])

---完整测试代码

---最终效果

2、res.redirect([status,] path)

---完整测试代码

---最终效果

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

---完整测试代码

---最终效果

4、res.status(code)

---完整测试代码

---最终效果


一、前言

上篇文章我们讲到express框架是如何通过express模拟Apache实现静态资源托管服务的一系列知识点,详情可见博文:Node.js后端开发 - 进阶篇 #6 express框架之通过express模拟Apache实现静态资源托管服务 这篇文章我们将介绍express框架中res(response)对象的一些常见方法

二、浏览中文官网API

我们可以先去 express中文官网:http://www.expressjs.com.cn/ 查看下的api文档,API参考手册--->4.x

我们可以看到它有五个对象,点击我们可以看到它们有很多方法,如下图:

             

          

三、res(response)对象的一些常见方法

1、res.json([body])

服务器端要向客服端响应json数据的时候,可以直接用res.json,下面是官网的一些介绍

Sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using JSON.stringify().

The parameter can be any JSON type, including object, array, string, Boolean, or number, and you can also use it to convert other values to JSON, such as null, and undefined (although these are technically not valid JSON).

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

---完整测试代码

//1、加载express模块
var express = require('express');

//2、创建app对象
var app = express();

app.get('/',function (req, res) {
    res.json({name: 'yyh', age: 22});
});

//3、启动服务
app.listen(3000, function (params) {
    console.log('http://localhost:3000');
});

---最终效果

这个 res.json() 其实和我们的 res.send() 是差不多的,你也可以发送 res.send({ name: 'yyh', age: 22 });  测试查看下,同时我们会发现它们响应的 Response Headers 消息头几乎完全一样

Connection: keep - alive
Content - Length: 23
Content - Type: application / json; charset = utf - 8
Date: Mon, 14 Oct 2019 01: 20: 45 GMT
ETag: W / "17-sVBK6dKTLTgMChflmeoQnyWQees"
X - Powered - By: Express

2、res.redirect([status,] path)

它是服务器端向浏览器发送重定向的,express把重定向的一系列操作封装到了 redirect方法 里面。

第一个参数可传可不传,如果不传参数它默认为302。就算我们传了http状态码,我们也不需要传http状态消息,因为对应的http状态码,有固定的http状态消息,它会自动判断这个状态码对应的http状态消息,然后帮我们添上,省去我们手动去填写了。

第二个参数path,相当于响应头里面那个location所对应的值 

下面这个是官网的一些介绍,详细可参考官网:http://www.expressjs.com.cn/4x/api.html#res.redirect

Redirects to the URL derived from the specified path, with specified status, a positive integer that corresponds to an HTTP status code . If not specified, status defaults to “302 “Found”.

res.redirect('/foo/bar');
res.redirect('http://example.com');
res.redirect(301, 'http://example.com');
res.redirect('../login');

---完整测试代码

//1、加载express模块
var express = require('express');

//2、创建app对象
var app = express();

app.get('/',function (req, res) {
    res.redirect('https://www.baidu.com');
    //res.redirect(301, 'https://www.baidu.com');
});

//3、启动服务
app.listen(3000, function (params) {
    console.log('http://localhost:3000');
});

---最终效果

我们在浏览器中输入地址:http://localhost:3000 ,会发现它直接跳转到百度了,这里就不截图了。然后我们可以查看它的响应消息头,点击一下左图的 view source ,我们会看到右图中的 状态码为302、location为百度链接

      

另外重定向一般以3开头,如:301、302等,它默认为302,我们也可以设置状态码为301看看效果 

res.redirect(301, 'https://www.baidu.com');

HTTP/1.1 301 Moved Permanently
X-Powered-By: Express
Location: https://www.baidu.com
Vary: Accept
Content-Type: text/html; charset=utf-8
Content-Length: 98
Date: Mon, 14 Oct 2019 02:05:29 GMT

所以说我们以后在服务器端做重定向的时候,就可以直接调用redirect方法了

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

res.sendFile() is supported by Express v4.8.0 onwards.

Transfers the file at the given path. Sets the Content-Type response HTTP header field based on the filename’s extension. Unless the root option is set in the options object, path must be an absolute path to the file.

这个方法在express 4.8.0 才开始有的,不用像以前用fs对象调用它的函数如createReadStream函数来进行一系列的操作,sendFile此方法读取操作已经给我们封装好了,我们基本上一句代码就可以搞定!

官网介绍连接:http://www.expressjs.com.cn/4x/api.html#res.sendFile

---完整测试代码

步骤1:

在当前项目的public目录下随便建立一个文件叫 xxx.txt 然后我输入内容:nodejs前端、后端开发

步骤2:

使用sendFile方法进行读取操作,响应给浏览器

//1、加载express模块
var express = require('express');
var path = require('path');

//2、创建app对象
var app = express();

app.get('/',function (req, res) {
    //使用sendFile方法进行读取操作,响应给浏览器
    res.sendFile(path.join(__dirname, 'public', 'xxx.txt'),function (err) {
        if(err){
            throw err;
        }else{
            console.log('ok');
        }
    });
});

//3、启动服务
app.listen(3000, function (params) {
    console.log('http://localhost:3000');
});

---最终效果

浏览器得到 sendFile方法读取 响应的消息

当访问成功,服务端输出消息  ok

MacBook-Pro:express-apache luminal$ node app
http://localhost:3000
ok

4、res.status(code)

Sets the HTTP status for the response. It is a chainable alias of Node’s response.statusCode.

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

它是用来设置响应状态码的,res.redirect重定向一般以3开头。如果我想来个404,以前我们响应404显示文件不存在这几个字,需要几行代码,这里不需要了,变得更简单!

res.status(404).send('文件不存在!');

---完整测试代码

//1、加载express模块
var express = require('express');
var path = require('path');

//2、创建app对象
var app = express();

app.get('/',function (req, res) {
    res.status(404).send('文件不存在!');
});

//3、启动服务
app.listen(3000, function (params) {
    console.log('http://localhost:3000');
});

---最终效果

我们在浏览器中输入:http://localhost:3000/ ,如下图

我们也可以查看下它的响应消息头

HTTP/1.1 404 Not Found
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 18
ETag: W/"12-PAojnk9dJEVQS3m3Y6TXhVfiRvY"
Date: Mon, 14 Oct 2019 03:37:59 GMT
Connection: keep-alive

猜你喜欢

转载自blog.csdn.net/YuDBL/article/details/102540869