GET 请求时 NodeJS 请求对象为空

NodeJS request object is empty on GET request

我有一个代码,我试图使用获取请求从下拉菜单中获取一些值。但是,当我单击提交时,请求对象为空。我确实使用了主体解析器和 bodyParser.json 并在路由之前声明了它们,但是请求对象仍然是空的:

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var EventHubClient = require('azure-event-hubs').Client;

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
console.log('');
};


app.get('/result', function(req, res){
  res.sendFile(__dirname + '/result.html');
});

app.get('/index', function(req,res) {
  res.sendFile(__dirname + '/index.html');
});

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

http.listen(3000, function(){
console.log('listening on *:3000');
});

这里是 index.html 文件:

<form id="tableForm" action="/getJson" method="get">
    <select class="selectpicker" data-style="btn-info" name="selectpicker">
        <optgroup label="Select Table">
            <option name="" value="0">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>
        </optgroup>
    </select>
    <input type="submit" />
</form>

在 index.html

的表单中尝试 post 方法

首先,您需要在 index.html 页面中将表单方法更改为 POST

<form id="tableForm" action="/getJson" method="get">
                                               ^^^

现在,由于方法是 POST 在您的 HTML 页面中,您也必须在此代码段中进行更改:

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

更改将反映为:

app.post('/getJson', function (req, res) {
    console.log(req.body);
    res.end();    //You must add this line as well.
});

你应该使用POST方法来传递数据。

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var EventHubClient = require('azure-event-hubs').Client;

const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
console.log('');
};


app.get('/result', function(req, res){
  res.sendFile(__dirname + '/result.html');
});

app.get('/index', function(req,res) {
  res.sendFile(__dirname + '/index.html');
});

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

http.listen(3000, function(){
console.log('listening on *:3000');
});

index.html

<form id="tableForm" action="/getJson" method="post">
    <select class="selectpicker" data-style="btn-info" name="selectpicker">
        <optgroup label="Select Table">
            <option name="" value="0">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>
        </optgroup>
    </select>
    <input type="submit" />
</form>