NodeJS从零开始构建Express的RESTful接口新手教程

288 阅读2分钟

「本文正在参与技术专题征文Node.js进阶之路,点击查看详情

一.构建一个web服务器

构建初始化项目

npm init -y

image.png

// 安装express
npm install express

// 创建app.js文件
touch app.js
// app.js
const express = require("express")
const app = express();
const port = 3000; // 服务端口

// 创建GET请求接口
app.get("/", (req,res)=>{
  res.send("Hello World")
})

app.listen(port,()=>{
  console.log("正在启动服务端口:"+port)
})

在package.json中设置启动脚本,后边再根据不同环境区分不同启动脚本

  "scripts": {
    "dev":"node app.js"
  },

image.png

在终端启动项目

npm run dev

image.png

然后在浏览器中访问http://127.0.0.1:3000/ 相当于GET请求了'/',说明服务构建成功 image.png

二.以GET, POST, PUT, DETELE形式的请求接口

Express的核心是中间件(中间函数),简单的说就是得到一个请求对象,要么要么反馈给客户端,要么传递给下一个中间件做处理,所以可以通过加载不同的中间件,做登录,日志等统一处理

2.1. 第三方中间件

例如morgan是作为请求日志中间件,helmet是安全防护中间件

npm install morgan helmet
// app.js
const morgan = require("morgan") // 请求日志
const helmet = require("helmet") // 安全防护中间件,使用helmet全部功能

const express = require("express")
const app = express();
const port = 3000;

app.use(helmet())
app.use(morgan("tiny"))

app.get("/", (req,res)=>{
  res.send("Hello World")
})

app.listen(port,()=>{
  console.log("正在启动服务端口:"+port)
})

2.2. 自定义中间件

例如自定义路由组件,先创建路由文件students.js

mkdir router && cd router
touch students.js

2.2.1 获取所有学生-(GET)

// router/students.js
const express = require("express");
const router = express.Router();

const students = [
  {id:1, name:"张三"},
  {id:2, name:"李四"},
  {id:3, name:"王五"},
]

// 获取所有学生
router.get("/", (req,res)=>{
  res.send({ msg:"success", data:students})
})

module.exports = router;

在app.js,引入加载路由students.js中间件

// app.js
const studentsRouter =  require("./router/students");
app.use("/api/students", studentsRouter); // 路由

Postman测试结果 image.png

2.2.2 根据id获取某个学生信息(GET)

这里值得注意是req.params.id,是获取前端请求路径的id参数值

// 根据id获取某个学生
router.get("/:id", (req,res)=>{
  const student = students.find(s=> s.id=== parseInt(req.params.id));
  if(!student) return res.status(404).send({msg:'未找到该学生',data:null});
  
  res.send({
    msg:"success",
    data:student
  })
})

Postman测试结果 image.png

2.2.3 增加学生(POST)

前端传入name参数,后端根据请求体获取name参数req.body.name ,值得注意的是这里解析不同前端传参方式,用到两种解析请求参数中间件, express.urlencoded和express.json

//app.js
app.use(express.urlencoded({ extended:true })) // 格式化key=value&key=value
app.use(express.json())    // JSON格式化req.body

x-www-from-urlencoded请求会将表单内的数据转换为键值对 image.png

JOSN的形式和传参 image.png

代码如下

// 增加学生
router.post("/", (req, res)=>{
  if(!req.body.name || req.body.name < 2) return res.status(400).send({ msg:"必须有名字,名字要大于等于两个字符",data:null})

  const student = {
    id: students.length +1,
    name: req.body.name
  }
  students.push(student);

  res.send({
    msg:"success",
    data:student
  })
})

Postman测试结果 image.png

2.2.4 根据id修改学生名字(PUT)

// 根据id修改学生名字
router.put("/:id", (req,res)=>{
  const student = students.find(s=> s.id === parseInt(req.params.id));
  if(!student) return res.status(404).send({msg:'未找到该学生',data:null,});

  if(!req.body.name || req.body.name < 2) return res.status(400).send({ msg:"必须有名字,名字要大于等于两个字符",data:null})

  student.name = req.body.name;

  res.send({
    msg:"success",
    data:student
  })
})

Postman测试结果 image.png

2.2.5 根据id删除某个学生(DETELE)

// 根据id删除某个学生
router.delete("/:id", (req,res)=>{
  const student = students.find(s=> s.id === parseInt(req.params.id));
  if(!student) return res.status(404).send({msg:'未找到该学生',data:null,});

  const index = students.indexOf(student)

  students.splice(index, index)

  res.send({msg:"success",data:student})
})

Postman测试结果 image.png

image.png

三.最后

代码已上传Github,下一篇再继续补充新手教程