koa2接收post请求参数formdata和json

表单提交时的请求类型为 `application/x-www-form-urlencoded`

原生的 HTML 表单 <form> 是没有 JSON 类型的,其总共有三种默认的格式,

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

默认为 application/x-www-form-urlencoded,可通过 <form> 表单的 enctype 指定。

所以真正意义上以 JSON 格式提交,需要借助 JavaScript,真实场景下表单也大多会走代码提交而非原生 submit 类型的 <button>

首页更新表单代码添加 onsubmit 方法:

- <form action="/save" method="POST">
+ <form action="/save" method="POST" οnsubmit="submitForm(event)" id="myForm">

添加以下代码到页面以提交表单:

<script>
    function submitForm(event) {
        event.preventDefault();
        var formData = new FormData(myForm);
        let data = {};
        for (var [key, value] of formData.entries()) {
            if (key.startsWith("hobbies")) {
            data["hobbies"]
                ? data["hobbies"].push(value)
                : (data["hobbies"] = [value]);
            } else {
            data[key] = value;
            }
        }

        fetch("/save", {
            method: "POST",
            headers: {
            "Content-Type": "application/json"
            },
            body: JSON.stringify(data)
        })
            .then(function(response) {
            return response.json();
            })
            .then(function(response) {
            console.log(response);
            });
    }
</script>

最后完整的后台与页面代码为:

server.js

var Koa = require("koa");
var Router = require("koa-router");
var fs = require("fs");
var bodyParser = require("koa-bodyparser");

var app = new Koa();
var router = new Router();

app.use(bodyParser());

router.get("/", async (ctx, next) => {
  ctx.type = "html";
  ctx.body = fs.createReadStream("index.html");
});

router.post("/save", async (ctx, next) => {
  ctx.body = ctx.request.body;
});

app.use(router.routes()).use(router.allowedMethods());
app.listen(3000);

console.log("server started at http:localhost:3000");

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>post json</title>
  </head>
  <body>
    <form action="/save" method="POST" οnsubmit="submitForm(event)" id="myForm">
      <div>
        <label for="name"
          >name:
          <input type="text" name="name" id="name" value="Tom" />
        </label>
      </div>
      <div>
        <label for="age"
          >age:
          <input type="number" name="age" id="age" value="19" />
        </label>
      </div>
      <div>
        <label
          >hobbies:
          <br />
          <input
            type="text"
            name="hobbies[0]"
            id="hobbies[0]"
            value="reading"
          />
          <br />
          <input type="text" name="hobbies[1]" id="hobbies[1]" value="music" />
          <br />
          <input type="text" name="hobbies[2]" id="hobbies[2]" value="swim" />
        </label>
      </div>
      <button type="submit">Submit</button>
    </form>
    <script>
      function submitForm(event) {
        event.preventDefault();
        var formData = new FormData(myForm);
        let data = {};
        for (var [key, value] of formData.entries()) {
          if (key.startsWith("hobbies")) {
            data["hobbies"]
              ? data["hobbies"].push(value)
              : (data["hobbies"] = [value]);
          } else {
            data[key] = value;
          }
        }

        fetch("/save", {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(data)
        })
          .then(function(response) {
            return response.json();
          })
          .then(function(response) {
            console.log(response);
          });
      }
    </script>
  </body>
</html>
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值