一、环境
1、安装express
npm i express@4.17.1 // 安装express模块
2、安装nodemon
npm i nodemon -g
3、运行命令
nodemon .\test.js
二、代码
1、代码结构:
- test.html为页面
- test.js为服务器端代码
- apiRouter为封装的路由模块
2、apiRouter.js
const express = require("express");
const database = require("mime-db");
const router = express.Router();
// 挂载对应的路由
router.get("/get", (req, res) => {
// 通过 req.query 获取客户端通过查询字符串,发送到服务器的数据
const query = req.query;
// 向客户端响应处理的结果
res.send({
status: 0, // 0成功,1失败
msg: "get请求成功!",
data: query, // 响应给客户端的数据
});
});
router.post("/post", (req, res) => {
// 通过 req.body 获取请求体中包含的 url-encoded 格式的数据
const body = req.body;
// 调用res.send方法,向客户端响应结果
res.send({
status: 0,
msg: 'POST请求成功!',
data: body
})
});
module.exports = router;
3、test.js
const express = require("express");
// 创建服务器实例
const app = express();
// 配置解析表单数据的中间件
app.use(express.urlencoded({ extended: false }));
// 一定要在路由之前,配置cors中间件,从而解决接口跨域问题
const cors = require("cors");
app.use(cors());
// 导入路由模块
const router = require("./apiRouter");
// 把路由挂载到app实例上
app.use("/api", router);
// 启动服务器
app.listen(8081, () => {
console.log("server running at http://127.0.0.1:8081");
});
4、test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<button id="btnGET">GET</button>
<button id="btnPOST">POST</button>
<script>
$(function () {
// 测试Get接口
$("#btnGET").on("click", function () {
$.ajax({
type: "GET",
url: "http://127.0.0.1:8081/api/get",
data: {
name: "zs",
age: 30,
},
success: function (res) {
console.log(res);
},
});
});
// 测试Post接口
$("#btnPOST").on("click", function () {
$.ajax({
type: "POST",
url: "http://127.0.0.1:8081/api/post",
data: {
bookname: "西游记",
author: "吴承恩",
},
success: function (res) {
console.log(res);
},
});
});
});
</script>
</body>
</html>
效果:
点击GET、POST按钮以后,控制台分别打印: