Express 的 req 和 res 对象

新建 learn-express文件夹,执行命令行

bash 复制代码
npm init -y
npm install express

新建 index.js

javascript 复制代码
const express = require('express');
const app = express();

app.get('/', (req, res, next) => {
    res.json('return get')
})

app.post('/', (req, res, next) => {
    res.json('return post')
})

app.listen(3000, () => {
    console.log('listen to 3000')
});

执行命令 nodemon ./index.js 。(nodemon是一个监视文件变化并自动重启应用程序的工具)

到 Postman 访问如下,都没有问题。

req

get

在 get 路由里打印一些开发中经常用到的属性,Postman发送get请求查询各属性信息:localhost:3000/info/123?name=jiawei

javascript 复制代码
app.get('/info/:id', (req, res, next) => {
    console.log('req.headers:', req.headers)
    console.log('req.ip:', req.ip)
    console.log('req.method:', req.method)
    console.log('req.protocol:', req.protocol)
    console.log('req.hostname:', req.hostname)
    console.log("req.url:", req.url)
    console.log('req.path:', req.path)
    console.log('req.query:', req.query)
    console.log('req.params:', req.params)
    res.json('return get')
})
// 请求结果:
req.headers: {
  'user-agent': 'PostmanRuntime/7.39.0',
  accept: '*/*',
  'postman-token': '4528f659-597c-4c09-a979-a1ddc97cb70c',
  host: 'localhost:3000',
  'accept-encoding': 'gzip, deflate, br',
  connection: 'keep-alive'
}
req.ip: ::1
req.method: GET
req.protocol: http
req.hostname: localhost
req.url: /info/123?name=jiawei
req.path: /info/123
req.query: { name: 'jiawei' }
req.params: { id: '123' }

这个 ::1是IPV6环回地址,代表我当前机器。

post

在Postman 使用 raw 的 json 格式发送post请求。

因为传过来的的是json,需要一个中间件来解析,添加代码 app.use(express.json()) 。

javascript 复制代码
app.use(express.json());
app.post('/', (req, res, next) => {
    console.log('req.body:', req.body)
    res.json('return post')
})
// 打印结果
req.body: { name: 'jiawei', age: 18 }

如果换成 x-www-form-urlencoded 格式发送post请求,也需要中间件解析。

javascript 复制代码
// extended: true 使用 queryString 库解析
// extended: false 使用 qs 库解析
app.use(express.urlencoded({ extended: true }));
// 打印结果
req.body: { name: 'jiawei', age: '18' }

res

res对象表示Express应用程序在收到HTTP请求时发送的HTTP响应。一些常用属性如下,更多详细内容移步官网查看。

res.json()

发送一个JSON响应,参数可以是任何JSON类型,包括对象、数组、字符串、布尔值、数字或null等等。

javascript 复制代码
res.json(null)
res.json({ name: 'jiawei' })
res.status(500).json({ error: 'message' })

res.end()

用于在没有返回任何数据的情况下快速结束响应。如果需要用数据来响应,可以使用res.send()和res.json()等方法。

javascript 复制代码
res.end()
res.status(404).end()

res.jsonp()

发送具有JSONP支持的JSON响应。JSONP默认回调名为callback,也可以通过设置 'jsonp callback name' 覆盖。具体例子

javascript 复制代码
res.jsonp({ name: 'jiawei' })
// => callback({ "name": "jiawei" })

// ?callback=foo
res.jsonp({ name: 'jiawei' })
// => foo({ "name": "jiawei" })

app.set('jsonp callback name', 'cb')
// ?cb=foo
res.jsonp({ "name": "jiawei" })
// => foo({ "name": "jiawei" })

res.render()

渲染视图,并将渲染后的HTML字符串发送给客户端。实践一下官网的例子。

安装模板引擎npm包Pug

bash 复制代码
npm install pug --save
javascript 复制代码
// 设置模板文件目录
app.set('views', './views')
// 设置视图引擎
app.set('view engine', 'pug')

创建一个名为index的Pug模板文件。在视图目录中,包含以下内容。

javascript 复制代码
html
  head
    title= title
  body
    h1= message

创建一个路由来渲染 index.pug

javascript 复制代码
app.get('/', function (req, res) {
  res.render('index', { title: 'Hey', message: 'Hello Express!' })
})

res.status()

设置响应的HTTP状态。它是 Node 的 response.statusCode 的一个可链接别名。

javascript 复制代码
res.status(403).end()
res.status(400).send('Bad Request')
res.status(404).sendFile('/absolute/path/to/404.png')

res.get()

返回由字段指定的HTTP响应头。匹配不区分大小写。

javascript 复制代码
res.set('Content-Type', 'application/json')
console.log('Content-Type:',res.get('Content-Type'))
console.log('content-type:', res.get('content-type'))
// 打印结果
Content-Type: application/json; charset=utf-8
content-type: application/json; charset=utf-8

res.set()

将响应的HTTP头字段设置为value。要一次设置多个字段可以传递一个对象作为参数。别名为res.header。

javascript 复制代码
app.post('/', function (req, res, next){
    // 写法1
    res.set('Content-Type', 'application/json')
    res.set('My-Name', 'jiawei')
    res.set('My-Age', 18)
    // 写法2
    // res.set({
    //     'Content-Type': 'application/json',
    //     'My-Name': 'jiawei',
    //     'My-age': 18
    // })
    // 写法3
    // res.header('Content-Type', 'application/json')
    // res.header('My-Name', 'jiawei')
    // res.header('My-Age', 18)
    // 写法4
    // res.header({
    //     'Content-Type': 'application/json',
    //     'My-Name': 'jiawei',
    //     'My-age': 18
    // })
    console.log(res.get('content-type'))
    console.log(res.get('My-Name'))
    console.log(res.get('My-Age'))
    console.log(res.getHeaders())
    res.end()
})
// 打印结果
application/json; charset=utf-8
jiawei
18
[Object: null prototype] {
  'x-powered-by': 'Express',
  'content-type': 'application/json; charset=utf-8',
  'my-name': 'jiawei',
  'my-age': '18'
}

res.download()

根目录下新建test.text,随意输入内容,例如"我是文本"。创建一个路由来处理下载请求。

javascript 复制代码
app.get('/download', function (req,res, next) {
    res.download('/test.txt')
})

Postman发起请求可以看到文本内容的,在浏览器中访问可以下载到该文件。

res.download 可自定义文件名和接收回调函数。

javascript 复制代码
// 自定义下载后的文件名为 report.pdf
res.download('/report-12345.pdf', 'report.pdf')
// 还可以接收回调函数,该函数在传输完成或发生错误时调用
res.download('/report-12345.pdf', 'report.pdf', function (err) {
  if (err) {
    // 处理错误,但请记住响应可能是部分发送的
    // 因此检查 res.headersSent
  } else {
    // 下载成功后,减少一个下载积分等等
  }
})
相关推荐
前端 贾公子2 天前
Express内置的中间件(express.json和express.urlencoded)格式的请求体数据
中间件·json·express
泯泷2 天前
老手机翻新!Express. js v5.0中的新功能
前端·后端·express
读心悦3 天前
express,生成用户登录后的 token
express
悦涵仙子4 天前
创建Express后端项目
前端·javascript·express
Ylucius7 天前
常见服务器大全----都是什么?又有何作用?区别联系是什么?---web,应用,数据库,文件,消息队列服务器,Tomat,Nginx,vite.....
java·前端·javascript·chrome·学习·node.js·express
计算机程序设计开发7 天前
基于Node.js+Express+MySQL+VUE实现的在线电影视频点播网站管理系统的设计与实现部署安装
vue.js·node.js·课程设计·express·计算机毕设·计算机毕业设计
计算机程序设计开发10 天前
基于Node.js+Express+MySQL+VUE新闻网站管理系统的设计与实现
数据库·mysql·node.js·课程设计·express·计算机毕设·计算机毕业设计
读心悦10 天前
express.js 链接数据库
javascript·数据库·express
JOJO___15 天前
Node.js Express中使用joi进行表单验证
node.js·express