当我将表单数据发布到路由时,获取未定义的参数错误。我无法将表单参数发送到路由文件。请帮我。这是我的代码,文件名为
获取错误
TypeError:无法读取未定义
的属性'username'
的node.js
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express();
var fs = require('fs');
var bodyParser = require('body-parser');
app.route('/').get(function(req,res) {
fs.readFile('./html/registers.html',function(err,data) {
res.writeHead(200,{'Content_type':'text/html'});
res.write(data);
res.end();
});
});
app.post('/formData', function(req, res) {
var username = req.body.username;
var password = req.body.password;
console.log("post received: %s %s", username, password);
});
register.js
<form action="formData" enctype="multipart/form-data" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" placeholder="Enter username" name="username">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="password" placeholder="Enter password" name="password">
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
答案 0 :(得分:1)
请替换以下
<form action="formData" enctype="multipart/form-data" method="post">
通过
<form action="/formData" method="post">
在路线功能之前添加以下
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));