如何将Node.js的输入存储到数据库

时间:2018-07-18 09:03:31

标签: mysql node.js

我已经创建了基本的HTML表单并将其显示在控制台上,我也使用nodejs创建了数据库。如何将server.js连接到database.js? 我的HTML文件

  <html>
   <body>
       <header className = "App-header" >
              <h1 className = "App-title" > Registration Form </h1>
        </header>
          <form action = "http://127.0.0.1:8081/process_get" method = "get">
              <label>
                <p>First Name:
                    <input type="text" name="first_name" /></p>
                <p>Last Name:
                    <input type="text" name="last_name" /></p>
                <p>Password:
                    <input type="password" name="password" /></p>
                <p>Mobile Number:
                    <input type="number" name="user_mobile" /></p>
                <p>Address:
                    <input type="text" name="user_address" /></p>
              </label>
                    <input type="submit" value="Submit"/>
          </form>
   </body>
</html>

我的server.js文件

app.use(express.static('public'));
app.get('/index.htm', function (req, res) {
   res.sendFile( __dirname + "/" + "index.htm" );
})

app.get('/process_get', function (req, res) {
   // Prepare output in JSON format
   response = {
      first_name:req.query.first_name,
      lastname:req.query.last_name,
      password:req.query.password,
      mobile:req.query.user_mobile,
      address:req.query.user_address
   };
   console.log(response);
   res.end(JSON.stringify(response));
})

我的databasejs文件

    var mysql = require('mysql');

var con = mysql.createConnection({
  host: "127.0.0.1",
  user: "root",
  password: "",
  database: "react"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  /*Create a table named "customers":*/
  var sql = "CREATE TABLE form (firstname VARCHAR(255),lastname VARCHAR(255),mobile INT,password VARCHAR(15), address VARCHAR(255))";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("Table created");
  });
});

如何将所有接收到的输入存储到数据库中

1 个答案:

答案 0 :(得分:1)

首先,您必须将databasejs文件导入或要求将其导入server.js。或者您也可以在其他地方执行此操作。

m <- matrix(rep(TRUE, nrow(df)), 5)
m[upper.tri(m)] <- FALSE
df[m,]
#    year value
# 1  2000     1
# 2  2001     2
# 3  2002     3
# 4  2003     4
# 5  2004     5
# 7  2001     2
# 8  2002     3
# 9  2003     4
# 10 2004     5
# 13 2002     3
# 14 2003     4
# 15 2004     5
# 19 2003     4
# 20 2004     5

然后进入您的路线

var db = require('path to databasejs ');