首页 > 解决方案 > 如何通过 post 方法发送开关切换表单

问题描述

我正在使用 ejs 模板并通过 method='post' 与 app.js 进行通信。我如何发送表格?

在输入文本的情况下,以下方法有效。

<form action="/login" method="POST">
            <div class="form-group">
              <label for="email">Email</label>
              <input type="email" class="form-control" name="username">
            </div>
            <div class="form-group">
              <label for="password">Password</label>
              <input type="password" class="form-control" name="password">
            </div>
            <button type="submit" class="btn btn-dark">Login</button>
</form>

但下面的切换切换表单并非如此。我怎样才能让它工作?

 <form action="/main" method="POST">
    <div class="custom-control custom-switch">
      <input type="checkbox" class="custom-control-input" id="sw1" name="toggle2">
      <label class="custom-control-label" for="sw1">On/Off</label>
    </div>
    <div class="custom-control custom-switch">
      <input type="checkbox" class="custom-control-input" id="sw2" name="toggle1">
      <label class="custom-control-label" for="sw2">on/off</label>
    </div>
    </form>

在服务器端,

app.post("/main",(req,res)=>{
  console.log(req.body.toggle1,req.body.toggle2);
});

它应该记录切换的项目,但没有返回任何内容。

app.js(服务器端)的几乎完整代码

 const app = express();
    const bodyParser = require("body-parser");
    app.use(bodyParser.urlencoded({extended: true}));
    app.get("/main",(req,res)=>{
      res.render("main");
    });
    app.post("/main",(req,res)=>{
      console.log(req.body.toggle1,req.body.toggle2);
    });

标签: javascriptmongodbexpressejs

解决方案


推荐阅读