Express教程【006】:使用Express写接口

文章目录

  • 8、使用Express写接口
    • [8.1 创建API路由模块](#8.1 创建API路由模块)
    • [8.2 编写GET接口](#8.2 编写GET接口)
    • [8.3 编写POST接口](#8.3 编写POST接口)

8、使用Express写接口

8.1 创建API路由模块

1️⃣新建routes/apiRouter.js路由模块:

js 复制代码
/**
 * 路由模块
 */
// 1-导入express
const express = require('express');
// 2-创建路由对象
const apiRouter = express.Router();

// 4-向外暴露路由对象
module.exports = apiRouter;

2️⃣注册路由模块:

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

const app = express();
// 导入路由模块
const apiRouter = require('./routes/apiRouter');
// 注册路由模块
app.use(apiRouter);

app.listen(80, ()=>{
    console.log('express server listening on http://127.0.0.1:80');
})

8.2 编写GET接口

1️⃣编写GET接口:

js 复制代码
// 编写GET请求
apiRouter.get("/get", (req, res) => {
    // 获取客户端通过查询字符串,发送到服务器的数据
    const query = req.query;
    res.send({
        status: 0,
        msg: 'GET请求成功',
        data: query
    })
})

2️⃣使用【postman】测试:

8.3 编写POST接口

1️⃣编写post请求:

js 复制代码
apiRouter.post('/add', (req, res) => {
    const body = req.body;
    res.send({
        status: 0,
        msg: 'POST请求成功',
        data: body,
    })
})

2️⃣配置json数据解析的中间件:

js 复制代码
// 配置解析json数据的中间件
app.use(express.json());

3️⃣使用【postman】测试:

测试接口:

http://127.0.0.1:80/add

测试的json数据:

json 复制代码
{
  "username": "John",
  "password": "1234"
}

测试结果:

相关推荐
Q_Q5110082852 天前
Nodejs+vue+ElementUI的校园外卖系统 骑手配送系统的设计与实现express-mysql
vue.js·elementui·express
神舟之光3 天前
jwt权限控制简单总结(乡村意见簿-vue-express-mongdb)
前端·vue.js·express
im_AMBER6 天前
万字长文:从零实现 JWT 鉴权
前端·react.js·express
zybsjn7 天前
一天快速实现markdown 编辑器和排版工具:基于Node.js + Express + 原生JS的开发实践
node.js·express·ai编程
codingWhat9 天前
用 Express 简单Mock自助终端机读取身份证
node.js·express
坐吃山猪12 天前
NodeJS极简后端服务
node·express
方寸猿12 天前
MindSharePCIe3.0-2 PCIe 体系结构概述- 2.1 PCI Express 简介-2.1.1 软件的后向兼容
express
@PHARAOH14 天前
WHAT - 替代 Express 和 Koa 的现代轻量版 Hono
前端·微服务·express·koa
品克缤15 天前
Trading-Analysis:基于“规则+LLM”的行情分析终端(兼谈 Vibe Coding 实战感)
前端·后端·node.js·vue·express·ai编程·llama