“如何解析Node JS中未定义的req.body”

时间:2019-05-05 00:55:02

标签: javascript sql node.js express

我正在设置一个节点js服务器,在我的req.body输出中,我一直未定义,我试图从表单Get request中请求SQL数据

我能够检索其他所有不涉及req.body的查询

var bodyParser = require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public'));
app.use(express.static(__dirname + '/public'));

app.get('/submit',urlencodedParser,function (req, res){
connection.connect(function (err) {
if (err) throw err;
console.log(req.body.lname);
var exist = req.body.lname;
var sql = "SELECT * FROM users WHERE lname= '" + exist + "'";

connection.query(sql, function(err,result) {
if (err) throw err;
console.log(result);
console.log(exist);
console.log(req.body.lname);
console.log("hello");
console.log(result);
});
});

'

输出:

未定义 [] 未定义 未定义 你好 []

1 个答案:

答案 0 :(得分:0)

获取请求不包含req.body对象。

您将不得不使用req.queryreq.params来传递数据或将获取的内容转换为帖子。

app.post('/submit', function(req, res) {
  connection.connect(function (err) {

    if (err) throw err;
    var exist = req.body.lname;
    var sql = "SELECT * FROM users WHERE lname= '" + exist + "'";

    connection.query(sql, function(err,result) {
        if (err) throw err;
        else console.log(result);
    });

});