如何从Node.js中的HTML表单创建SQL查询?

时间:2017-11-07 20:26:34

标签: javascript sql-server node.js

我有一个接受2个文本字段的表单和1个带3个选项的单选按钮。我想将这3个输入转换为SQL(MS SQL Server)INSERT INTO语句,以在数据库中创建新用户。如果我为request.input的value参数使用文字,但是如果我将value参数更改为req.body.first_name之类的其他内容,它仍会在我的数据库中创建一个新行,但所有3个字段都是NULL 。任何帮助将不胜感激!

这是我的简单形式:

<!doctype html>
<html lang="en">
  <head>
    <title>Users</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="E:\Projects\node_modules\bootstrap\dist\css\bootstrap.css">
  </head>
  <body>
    <h1><center>Add a new user</center></h1><br>

    <center>
      <form action = "http://127.0.0.1:8080/api/user" method = "POST" enctype = "multipart/form-data">
         <input type ="text" name ="first_name" placeholder="Enter First Name"><br>
         <br>
         <input type ="text" name = "last_name" placeholder="Enter Last Name"><br>
         <br>
         <input type="radio" name="gender" id="male" value="male"> Male
         <input type="radio" name="gender" id="female" value="female"> Female
         <input type="radio" name="gender" id="other" value="other"> Other<br>
         <br>
         <input type = "submit" value = "Submit">
      </form><br>
    </center>

    <h1><center>List all users</center></h1><br>

    <center>
      <form action = "http://127.0.0.1:8080/api/user" method = "GET">
         <input type = "submit" value = "Go get'em!">
      </form>
    </center>

    <!-- Optional JavaScript -->
      <script src="sql.js"></script>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
  </body>
</html>

这是我的Node.js文件(是的,我有2个POST API。当我尝试找出正在进行的操作时,有一个被注释掉。所以我的POST URL看起来像这样{{ 1}}

localhost:8080/api/user?first_name=Timmy&last_name=Johnson&gender=Male:

1 个答案:

答案 0 :(得分:0)

好吧,经过一些头到键的敲击就是我自己的问题的答案。

我有两个问题。 第一个问题出在我的“用户输入”表单中。我对enctype = "multipart/form-data"的含义感到困惑,我的表单正在发布,并且正在编码我的表单数据,这是完全没必要的。所以我从表单中删除了它。

第二个问题在于构建我的SQL查询。我让事情变得复杂了。另外,我有一些额外的东西,只是不需要@SLaks指出。所以,这是最终的Node.js代码,其中包含有效的POST代码:

//Initiallising node modules
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var sql = require("mssql");

// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: true }));

//Setting up server
var server = app.listen(process.env.PORT || 8080, function () {
  var port = server.address().port;
  console.log("App now running on port", port);
});

// Configure database connection
var dbConfig = {
  user: 'user',
  domain: 'domain',
  password: 'password',
  server: 'dbserver',
  database: 'database'
};

//Function to connect to database and execute query
var  executeQuery = function(res, query){
  sql.connect(dbConfig, function (err) {
    if (err) {
      console.log("Error while connecting database :- " + err);
      res.send(err);
    }
    else {
      // create Request object
      var request = new sql.Request();
      // query to the database
      request.query(query, function (err, rs) {
        if (err) {
          console.log("Error while querying database :- " + err);
          res.send(err);
        }
        else {
          res.send(rs);
          sql.close();
        }
      });
    }
  });
};

//GET API
app.get("/api/user", function(req , res){
  var query = "select * from [Names]";
  executeQuery (res, query);
});

//POST API
app.post("/api/user", function(req , res){
  var formData = {
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    gender: req.body.gender
  };

  var query = `INSERT INTO Names (First_Name,Last_Name,Gender) VALUES ('${formData.first_name}', '${formData.last_name}', '${formData.gender}')`;
  console.log(query);
  executeQuery (res, query);
});