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"
}

测试结果:

相关推荐
一袋米扛几楼9818 小时前
【报错问题】解决 Vercel 部署报错:Express 类型失效与 TypeScript 2349/2339/2769 错误排查
ubuntu·typescript·express
懒人村杂货铺2 天前
Express + TypeScript 后端通用标准规范
javascript·typescript·express
前端小超人rui3 天前
【Node.js Express中间件理解及中间件分类和作用】
中间件·node.js·express
前端小超人rui3 天前
封装Express 自定义中间件
中间件·node.js·express
Aolith3 天前
从前端模拟到全栈认证:我的论坛 JWT 实战复盘
node.js·express
Aolith6 天前
全栈论坛笔记:异步、HTTP 与安全基础
express
Aolith8 天前
学 Express 被 app.use 绕晕了?用流水线思维一次性搞懂 5 种中间件
后端·express
森叶8 天前
告别端口占用!用 Unix Domain Socket 管道让 Express 飞起来
服务器·unix·express
Aolith11 天前
《Express 初学者笔记:再也不怕搞混 req 和 res 了》
express
炽烈小老头11 天前
Express Routing(路由系统)
node.js·express