【问题标题】:Insert data from form into MYSQL using Node JS使用 Node JS 将表单中的数据插入 MYSQL
【发布时间】:2015-09-19 13:26:59
【问题描述】:

我正在尝试使用节点和 Express 框架从 HTML 表单将数据插入 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但无法将数据插入数据库请指出我做错的地方。

提前致谢。

【问题讨论】:

    标签: html mysql node.js express


    【解决方案1】:

    这是我的 js 文件-

    var express = require("express");
    var app     = express();
    var path    = require("path");
    var mysql = require('mysql');
    var bodyParser = require('body-parser');
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "",
      database: "mydb"
    });
    app.get('/',function(req,res){
      res.sendFile(path.join(__dirname+'/index.html'));
    });
    app.post('/submit',function(req,res){
    
      var name=req.body.name;
      var email=req.body.email;
      var username=req.body.username;
      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 username "' + req.body.username+'".\n');
    
      con.connect(function(err) {
      if (err) throw err;
      var sql = "INSERT INTO form (name, email,description) VALUES ('"+name+"', '"+email+"','"+username+"')";
      con.query(sql, function (err, result) {
        if (err) throw err;
        console.log("1 record inserted");
         res.end();
      });
      });
    })
    app.listen(3000);
    console.log("Running at Port 3000");
    

    这是我的 html 文件-

    <html>
    <head>
        <title> test </title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    </head>
        <body>
            <form action="/submit" method="POST">
                <fieldset>
                    <label for="name">Name: </label>
                    <input type="text" id="name" name="name" autofocus />
                    <br/>
                    <label for="email">Email: </label>
                    <input type="email" id="email" name="email"  />
                    <br/>
                    <label for="username">User name: </label>
                    <input type="textbox" id="username" name="username" />
                    <br/>
                    <input type="submit" value="create profile" />
                </fieldset>
            </form>
        </body>
    </html>
    

    【讨论】:

    • 虽然此代码 sn-p 可能是解决方案,但包含解释确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因
    【解决方案2】:

    你可以试试这个

    我正在使用 node 中的 express js 执行此操作 先决条件:安装node js,mysql,express,express-generator

    写在 index.jade 文件中

    <html>
    <head>
    <title> test </title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    </head>
    <body>
    <form action="/submitform/" method="POST">
    <fieldset>
    <label for="name">Name: </label>
    <input type="text" id="name" name="name" autofocus />
    <br/>
    <label for="email">Email: </label>
    <input type="email" id="email" name="email"  />
    <br/>
    <label for="description">Description: </label>
    <textarea id="description" name="description"></textarea>
    <br/>
    <input type="submit" value="create profile" />
    </fieldset>
    
    </form>
    </body>
    </html>
    

    然后,把这个写在 index.js 文件中

    var express = require('express');
    var router = express.Router();
    var mysql = require('mysql');
    var con = mysql.createConnection({
         host: "localhost",
         user: "root",
         password: "",
         database: "testn"
    });
    
    router.post('/submitform', function(req, res, next) {
        console.log(req.body.name);
        console.log(req.body.email);
        console.log(req.body.description);
        con.connect(function(err) {
      if (err) throw  err;
      console.log("connected");
      var sql = "INSERT INTO `form`(`name`,`email`, `description`) VALUES ('"+req.body.name+"','"+req.body.email+"','"+req.body.description+"')";
      con.query(sql, function(err, result)  {
       if(err) throw err;
       console.log("table created");
      });
    });
    
      res.render('index', { title: 'Express' });
    });
    
    
    module.exports = router;
    

    此代码会将表单中的值插入到节点 js 中的 MySql

    希望对你有帮助

    【讨论】:

      【解决方案3】:
      var express = require('express');
      var app = express();
      var ejs = require('ejs');
      var pg = require('pg');
      var bodyParser = require('body-parser');
      app.use(bodyParser.urlencoded({ extended: true })); 
      
      
              var conString = process.env.DATABASE_URL || "postgres://postgres:Emdsystems@localhost:5432/student";
              var client = new pg.Client(conString);
              client.connect();
      
      app.get('/',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()
      
      client.query("Insert into record (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');
      

      【讨论】:

      • 加油!他询问有关保存 MySQL 数据库的问题,但您提供的是 postgres 的解决方案pg = require('pg')
      【解决方案4】:

      试试这个

      mysql.query('select id, name, price from ' + TABLE + ' where price < 100',
      function(err, result, fields) {
          if (err) throw err;
          else {
              console.log('Gadgets which costs less than $100');
              console.log('----------------------------------');
              for (var i in result) {
                  var gadget = result[i];
                  console.log(gadget.name +': '+ gadget.price);
              }
          }
      });
      

      参考:http://www.hacksparrow.com/using-mysql-with-node-js.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-16
        • 2018-06-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多