node.js的express模块实现GET和POST请求

一、环境

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按钮以后,控制台分别打印:

 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想做一只快乐的修狗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值