在POST express nodejs中,req.body是空的

时间:2017-11-16 14:19:55

标签: jquery node.js express post body-parser

以下是我在服务器端发布数据的HTML表单代码。

HTML代码:

<form action="/Device_Data" method="post">
    <select name="deviceSelect" id="deviceSelect" class="selectdevice" type = "text" style="margin-top:1.5%">
        <option value="" selected="selected">Choose Device</option>
        <option value="Device1">Device 1</option>
        <option value="Device2">Device 2</option>
        <option value="Device3">Device 3</option>
        <option value="Device4">Device 4</option>
        <option value="Device5">Device 5</option>
        <option value="Device6">Device 6</option>
        <option value="Device7">Device 7</option>
        <option value="Device8">Device 8</option>
    </select>
    <button id="Import" value="Import" class="button1" type="button" formenctype="text/plain">Import</button>
</form>

服务器代码:

var express = require('express');
//require the body-parser nodejs module
var bodyParser = require('body-parser');
var path = require('path');
var qs = require('querystring');
var app = express();
// var server = http.createServer(app);

//support parsing of application/json type post data
app.use(bodyParser.json());

//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: false }));

app.post("/Device_Data", function (req, res) {

  // result.entries contains entities matching the query
 //res.setHeader('Content-Type', 'application/json');
  console.log(req.body);
  res.send(200, req.body);
});

输出:

{}
Thu, 16 Nov 2017 14:05:13 GMT express deprecated res.send(status, body): Use res.status(status).send(body) instead at server.js:122:7

任何人都可以帮助我吗? 提前谢谢。

我只想打印req.body数据。

2 个答案:

答案 0 :(得分:0)

就像错误所说的那样,不推荐使用语法res.send(status, body):

更改以下代码:

res.send(200, req.body);

要:

res.status(200).send(req.body);

有关更多信息,请参阅: http://expressjs.com/en/api.html

答案 1 :(得分:0)

将按钮的type更改为提交,然后从此按钮中移除formenctype

 <button id="Import" value="Import" class="button1" type="submit">Import</button>