title: How can I create a SQL query from an HTML form in Node.js?
body: <p>I have a form that accepts 2 text fields and 1 radio button with 3 options. I'd like to turn those 3 inputs into a SQL (MS SQL Server) <code>INSERT INTO</code> statement to create a new user in a database. It works if I user literals for the value parameter of my request.input but if I change the value parameter to something else like <code>req.body.first_name</code> it still creates a new row in my database but all 3 fields are <code>NULL</code>. Any help would be greatly appreciated!</p>
  
  <p>Here is my simple form:</p>
  
  <pre><code>&lt;!doctype html&gt;
  &lt;html lang="en"&gt;
    &lt;head&gt;
      &lt;title&gt;Users&lt;/title&gt;
      &lt;!-- Required meta tags --&gt;
      &lt;meta charset="utf-8"&gt;
      &lt;meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"&gt;
  
      &lt;!-- Bootstrap CSS --&gt;
      &lt;link rel="stylesheet" href="E:\Projects\node_modules\bootstrap\dist\css\bootstrap.css"&gt;
    &lt;/head&gt;
    &lt;body&gt;
      &lt;h1&gt;&lt;center&gt;Add a new user&lt;/center&gt;&lt;/h1&gt;&lt;br&gt;
  
      &lt;center&gt;
        &lt;form action = "http://127.0.0.1:8080/api/user" method = "POST" enctype = "multipart/form-data"&gt;
           &lt;input type ="text" name ="first_name" placeholder="Enter First Name"&gt;&lt;br&gt;
           &lt;br&gt;
           &lt;input type ="text" name = "last_name" placeholder="Enter Last Name"&gt;&lt;br&gt;
           &lt;br&gt;
           &lt;input type="radio" name="gender" id="male" value="male"&gt; Male
           &lt;input type="radio" name="gender" id="female" value="female"&gt; Female
           &lt;input type="radio" name="gender" id="other" value="other"&gt; Other&lt;br&gt;
           &lt;br&gt;
           &lt;input type = "submit" value = "Submit"&gt;
        &lt;/form&gt;&lt;br&gt;
      &lt;/center&gt;
  
      &lt;h1&gt;&lt;center&gt;List all users&lt;/center&gt;&lt;/h1&gt;&lt;br&gt;
  
      &lt;center&gt;
        &lt;form action = "http://127.0.0.1:8080/api/user" method = "GET"&gt;
           &lt;input type = "submit" value = "Go get'em!"&gt;
        &lt;/form&gt;
      &lt;/center&gt;
  
      &lt;!-- Optional JavaScript --&gt;
        &lt;script src="sql.js"&gt;&lt;/script&gt;
      &lt;!-- jQuery first, then Popper.js, then Bootstrap JS --&gt;
      &lt;script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"&gt;&lt;/script&gt;
      &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"&gt;&lt;/script&gt;
      &lt;script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"&gt;&lt;/script&gt;
    &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>And here is my Node.js file (yes I have 2 POST APIs. One is commented out while I try and figure out what's going on. So my <code>POST URL</code> should look like this <code>localhost:8080/api/user?first_name=Timmy&amp;last_name=Johnson&amp;gender=Male:</code></p>
  
  <pre><code>//Initiallising node modules
  var express = require('express');
  var app = express();
  var bodyParser = require('body-parser');
  var sql = require("mssql");
  var form = require('multer');
  
  // Body Parser Middleware
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  var urlencodedParser = bodyParser.urlencoded({ extended: false });
  app.use(bodyParser.text({ type: 'text/html' }));
  
  //CORS Middleware
  app.use(function (req, res, next) {
      //Enabling CORS
      res.header("Access-Control-Allow-Origin", "*");
      res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
      res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
      next();
  });
  
  //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: 'server',
      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) {
      res.setHeader('Content-Type', 'text/plain');
      // connect to your database
      sql.connect(dbConfig, function (err) {
          if (err) console.log(err);
  
          // create Request object
          var request = new sql.Request();
          request.input('first_name',sql.VarChar,req.body.first_name);
          request.input('last_name',sql.VarChar,req.body.last_name);
          request.input('gender',sql.VarChar,req.body.gender);
  
          request.query("INSERT INTO Names (First_Name, Last_Name, Gender) VALUES (@first_name, @last_name, @gender)", function (err, recordset) {
              if (err) console.log(err);
              // send records as a response
              res.send(recordset);
              sql.close();
          });
      });
  });
  
  // //POST API
  //  app.post("/api/user", function(req , res){
  //                 //var query = "INSERT INTO Names (First_Name, Last_Name, Gender) VALUES ('Test', 'User', 'Female')";
  //                 var query = "INSERT INTO Names (First_Name,Last_Name,Gender) VALUES ()";
  //                 executeQuery (res, query);
  // });
  
  //PUT API
   app.put("/api/user/:id", function(req , res){
                  var query = "UPDATE [Names] SET First_Name= " + req.body.first_name  +  " , Last_Name=  " + req.body.last_name + " , Gender=  " + req.body.gender + "  WHERE Id= " + req.params.id;
                  executeQuery (res, query);
  });
  
  // DELETE API
   app.delete("/api/user/:id", function(req , res){
                  var query = "DELETE FROM [Names] WHERE Id=" + req.params.id;
                  executeQuery (res, query);
  });
  </code></pre>