简体   繁体   中英

req.body is undefined by body-parser

I tried every possible solutions that I found, but none of them working. The body-parser is installed, the front-end is also correct. When I send a form, the url is

/addChess?name=123&hp=123&damage=123&skill=1&class=1

However, the req.body is undefined. My code:

  var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();

// DataBase 
var mysql = require("mysql");

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "chess"
});

con.connect(function(err) {
    if (err) {
        console.log('connecting error');
        return;
    }
    console.log('connecting success');
});



// view engine setup
app.set('views', path.join(__dirname, '/views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/public')));

// db state
app.use(function(req, res, next) {
    req.con = con;
    next();
});


app.get('/', function(req, res, next) {
    var db = req.con;

    db.query('SELECT chess.name AS name, chess.health AS health, chess.damage AS damage, skill.name AS skill, class.name AS class FROM chess, skill, class WHERE chess.class = class.classID AND chess.skillID = skill.skillID', function(err1, rows1) {
        if (err1) {
                    console.log(err1);
                }
        db.query('SELECT name,skillID FROM skill',function(err2, rows2){
            if (err2) {
                    console.log(err2);
                }
            db.query('SELECT name,classID FROM class',function(err3, rows3){
                if (err3) {
                    console.log(err3);
                }
                res.render('index', {data: rows1, skillList: rows2, classList:rows3});
            });
        });
    });

});

app.get('/addChess', function(req, res, next) {
    var db = req.con;

    var sql = {
        name: req.body.name,
        health: req.body.hp,
        damage: req.body.damage,
        skillID: req.body.skill,
        class: req.body.class
    };

    //console.log(sql);
    var qur = db.query('INSERT INTO chess SET ?', sql, function(err, rows) {
        if (err) {
            console.log(err);
        }

        res.setHeader('Content-Type', 'application/json');
        console.log(qur.sql); 
        console.log(req.headers);
        res.redirect('/');
    });
});

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("Example app listening at http://%s:%s", host, port)
})

module.exports = app;

These are not body params but ordinary request parameters. Use req.query.name etc instead. Check the documentation here: http://expressjs.com/en/api.html#req.query

Body parameters is what you usually pass when doing an HTTP POST request.

When you submit a form using the GET HTTP method, the form fields are sent in the querystring, which is not parsed by the body-parser module. For parsing the querystring, you can use url.parse(req.url, true).querystring .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM