' app.js'我有
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
' index.js'完整代码
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
router.get('/', function(req, res, next) {
res.render('index', { title: 'Here' });
});
router.post('/manager', function(req, res, next) {
var connection = mysql.createConnection({
host : 'localhost',
user : req.body.username,
password : req.body.password,
database : 'shops'
});
connection.connect(function(err){
if(!err)
res.render('manager', { title: 'Here' });
else
console.log("Error connecting database ...");
});
});
module.exports = router;
在' index.html'登录表单
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' type='text'><br>
Password<br>
<input id='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>
在index.js第12-13行
req.body.username
req.body.password
每当我尝试从html表单解析数据时,它们都会返回“未定义”。我是node.js脚本的新手。我做错了吗?
答案 0 :(得分:4)
您的name
代码上缺少<input>
个属性。添加如下:
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' name='username' type='text'><br>
Password<br>
<input id='password' name='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>