我正在尝试使用 HTML 表单中的节点和 Express 框架将数据插入 MySQL。表格的代码是:
<html>
<head>
<title>Personal Information</title>
</head>
<body>
<div id="info">
<h1>Personal Information</h1>
<form action="/myaction" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your full name" />
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email address" />
<br><br>
<label for="city">City:</label>
<input type="text" id="city" name="city" placeholder="Enter your city" />
<br><br>
<label for="pincode">Pincode:</label>
<input type="text" id="pincode" name="pincode" placeholder="Enter your pincode" />
<br><br>
<input type="submit" value="Send message" />
</form>
</div>
</body>
</html>
.js 文件是:
var express = require('express');
var app = express();
var ejs = require('ejs');
var mysql = require('mysql');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
var HOST = 'localhost';
var PORT = 3000
var MYSQL_USER = 'root';
var MYSQL_PASS = 'jelly123#';
var DATABASE = 'form';
var TABLE = 'info';
var mysql = mysql.createConnection({
host: HOST,
port: PORT,
user: MYSQL_USER,
password: MYSQL_PASS,
});
app.get('/home',function(req,res,next){
res.sendfile('views/forms.html');
});
app.post('/myaction', function(req, res) {
console.log('req.body');
console.log(req.body);
res.write('You sent the name "' + req.body.name+'".\n');
res.write('You sent the Email "' + req.body.email+'".\n');
res.write('You sent the City "' + req.body.city+'".\n');
res.write('You sent the Pincode "' + req.body.pincode+'".\n');
res.end()
mysql.query("Insert into "+TABLE+" (name,email,city,pincode) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.city+"','"+req.body.pincode+"')",function(err, result)
{
if (err)
throw err;
});
});
app.listen(3000);
console.log('Example app listening at port:3000');
我能够输入表单数据并将其显示在页面 http://localhost:3000/myaction 但无法将数据插入数据库请指出我做错的地方。
提前致谢。
原文由 Anshul Garg 发布,翻译遵循 CC BY-SA 4.0 许可协议