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

测试结果:

相关推荐
Dream_Ji3 天前
Express使用教程(二)
express
Json____12 天前
使用node-Express框架写一个学校宿舍管理系统练习项目-前后端分离
node·express·前后端分离·宿舍管理
草木红14 天前
express 框架基础和 EJS 模板
arcgis·node.js·express
HWL567921 天前
在本地使用Node.js和Express框架来连接和操作远程数据库
node.js·express
SEO-狼术21 天前
Add-in Express for Microsoft Office
microsoft·express
盛夏绽放1 个月前
Node.js 和 Express 面试问题总结
面试·职场和发展·node.js·express
天天进步20151 个月前
Node.js中Express框架入门教程
node.js·express
mosen8681 个月前
易混淆的CommonJS和ESM(ES Module)及它们区别
javascript·node.js·express
一枚小小程序员哈1 个月前
基于Vue + Node能源采购系统的设计与实现/基于express的能源管理系统#node.js
vue.js·node.js·express
一枚小小程序员哈1 个月前
基于Vue的个人博客网站的设计与实现/基于node.js的博客系统的设计与实现#express框架、vscode
vue.js·node.js·express