首页 > 解决方案 > 使用 express 在 node.js 中获取选定的选项值

问题描述

我需要使用 express 获取所选对象以在 app.js 中对其进行控制台

例子.html

 <form id="tableForm" action="getJson">
        <select class="example" name="example">
              <option name="" value="0" selected>Select table</option>
              <option name="table1" value="1">Table 1</option>
              <option name="table2" value="2">Table 2</option>
              <option name="table3" value="3">Table 3</option>
        </select>
    </form>

应用程序.js

var express = require('express'),
app = express();

app.use(express.bodyParser());

 app.get('/', function(req, res){
  res.sendfile('views/index.html');
});

app.get('/getJson', function (req, res) {
   console.log(req.body.example);
});

app.listen(3000, function(){
    console.log('Server running at port 3000: http://127.0.0.1:3000')
});

即使我选择另一个对象,控制台的输出也是未定义的。

标签: htmlnode.jsexpressejs

解决方案


您需要为post表单提交的方法添加处理程序。

应用程序.js

app.post('/getJson', function (req, res) {
   console.log(req.body.example);
});

例子.html

<form method="post" id="tableForm" action="getJson">
  <select class="example" name="example">
      <option name="" value="0" selected>Select table</option>
      <option name="table1" value="1">Table 1</option>
      <option name="table2" value="2">Table 2</option>
      <option name="table3" value="3">Table 3</option>
  </select>
</form>

推荐阅读