我尝试了我找到的所有可能的解决方案,但没有一个能够正常工作。安装了body-parser,前端也正确。当我发送表格时,网址是
/ addChess名称= 123&安培;马力= 123&安培;损伤= 123&安培;技能= 1&安培;类= 1
但是,req.body未定义。我的代码:
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;
答案 0 :(得分:2)
这些不是身体参数,而是普通的请求参数。请改用req.query.name等。请查看此处的文档:http://expressjs.com/en/api.html#req.query
正文参数是您在执行HTTP POST请求时通常传递的内容。
答案 1 :(得分:0)
使用GET HTTP方法提交表单时,表单字段将在查询字符串中发送,而body-parser
模块不会对其进行解析。要解析查询字符串,可以使用url.parse(req.url, true).querystring
。