当前位置: 首页 > article >正文

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

文章目录

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

8、使用Express写接口

8.1 创建API路由模块

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

/*** 路由模块*/
// 1-导入express
const express = require('express');
// 2-创建路由对象
const apiRouter = express.Router();// 4-向外暴露路由对象
module.exports = apiRouter;

2️⃣注册路由模块:

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接口:

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

2️⃣使用【postman】测试:

image-20250603100503420

8.3 编写POST接口

1️⃣编写post请求:

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

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

// 配置解析json数据的中间件
app.use(express.json());

3️⃣使用【postman】测试:

测试接口:

http://127.0.0.1:80/add

测试的json数据:

{"username": "John","password": "1234"
}

测试结果:

image-20250603102434712

http://www.lryc.cn/news/2398164.html

相关文章:

  • mongodb集群之分片集群
  • Starrocks Full GC日志分析
  • 飞算 JavaAI 赋能老项目重构:破旧立新的高效利器
  • RockyLinux9安装Docker
  • RequestRateLimiterGatewayFilterFactory
  • 解决 xmlsec.InternalError: (-1, ‘lxml xmlsec libxml2 library version mismatch‘)
  • 【Linux基础知识系列】第九篇-Shell脚本入门
  • typescript的Interface和Type
  • java后端生成心电图-jfreechart
  • 算法/机理模型演示平台搭建(二)——算法接口部署(FastApi)
  • 动态规划-647.回文子串-力扣(LeetCode)
  • es 的字段类型(text和keyword)
  • Kotlin 中companion object {} 什么时候触发
  • 仿真每日一练 | Workbench中接触种类及选择方法简介
  • Go语言中的rune和byte类型详解
  • superior哥AI系列第6期:Transformer注意力机制:AI界的“注意力革命“
  • 【java面试】redis篇
  • 高效易用的 MAC 版 SVN 客户端:macSvn 使用体验
  • 【搭建 Transformer】
  • 自然图像数据集
  • Linux下使用nmcli连接网络
  • HCIP(BGP综合实验)
  • Attention Is All You Need (Transformer) 以及Transformer pytorch实现
  • uniapp+vue2+uView项目学习知识点记录
  • 精美的软件下载页面HTML源码:现代UI与动画效果的完美结合
  • 车载诊断架构 --- DTC消抖参数(Trip Counter DTCConfirmLimit )
  • javaEE->IO:
  • Oracle 用户/权限/角色管理
  • 使用免费wordpress成品网站模板需要注意点什么
  • 深入理解 JSX:React 的核心语法