简体   繁体   中英

Integrating Frontend Javascript with Backend Node.Js and mySQL

I have tried searching around, but could not really find a solution to my question. Either that or I am not really understanding something properly.

I have a page with a simple form that uses Javascript to alert the user of their inputs upon clicking the submit button. I've also created a Node.Js function to insert input into a mySQL database. What I am unsure of is if I am able to link the above together without using a framework like Express Js.

My codes as follows:

index.php

<!doctype html>
<html>
<head>
  <title>homework</title>
  <link href="../css/style.css" rel="stylesheet" type="text/css"/>
  <script src="../js/form.js"></script>
</head>
<body>
  <div class="container">
    <h1>This is a header</h1>
    <div class="card input-form">
      <p>Enter your details below.</p>
      <label for="inputFirstName">First Name</label>
      <input id="inputFirstName" type="text" name="inputFirstName" required /><br><br>
      <label for="inputLastName">Last Name</label>
      <input id="inputLastName" type="text" name="inputLastName" required /><br><br>
      <button id="btnSubmit" onclick="submitDetails();">Submit</button>
    </div>
  </div>

</body>
</html>

form.js

let firstName, lastName, response;

function submitDetails() {
  firstName = document.getElementById("inputFirstName").value;
  lastName = document.getElementById("inputLastName").value;

  response = confirm(`Please verify the submitted details.

First Name: ${firstName}
Last Name: ${lastName}`);

  if (response == true) {
    alert("Personal details submitted.");
  } else {
    alert("You have cancelled your submission.");
  }
}

app.js

const mysql = require("mysql");
const config = require("./config.js");
// console.log(config);
const connection = mysql.createConnection(config);

connection.connect((err) => {
  if (!err) {
    console.log("Connected to mySQL Database");
  } else {
    console.log("Connection Failed");
  }
});

const newTable = `CREATE TABLE IF NOT EXISTS details (
                  id int primary key auto_increment,
                  firstName varchar(50) NOT NULL,
                  lastName varchar(50) NOT NULL
                )`;

connection.query(newTable, function (err, results, fields) {
  // console.log(results);
});

module.exports = connection;

let firstName, lastName;

function insertEntry(firstName, lastName) {
  firstName = "John";
  lastName = "Doe";

  let newEntry = `INSERT INTO details (firstName, lastName)
                  VALUES ('${firstName}', '${lastName}')`;

  connection.query(newEntry, function (err, results, fields) {
    // console.log(results);
    if (!err) {
      console.log("Entry inserted into table");
    }
  });
}

insertEntry();

connection.end(function () {
  console.log("Connection Terminated");
});

config.js

let config = {
  host: "127.0.0.1",
  user: "test",
  password: "password",
  database: "homework",
};

module.exports = config;

My Folder Tree is as such:

homework
|--views
| |--index.php
|
|--js
| |--app.js
| |--config.js
| |--form.js
|
|--css
  |--style.css

======================================================

Update using Fedex7501's answer:

app.js

var http = require("http");
var fs = require("fs");
http
  .createServer(function (req, res) {
    if (req.method === "POST") {
      let body = "";
      req.on("data", (chunk) => {
        body += chunk.toString();
      });
      req.on("end", () => {
        body = JSON.parse(body);
        insertEntry(body.firstName, body.lastName);

        // res.end("ok");
      });
      // } else {
      //   res.end();
    }
    fs.readFile("../views/index.php", function (err, data) {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.write(data);
      return res.end();
    });
  })
  .listen(8000);

const mysql = require("mysql");
const config = require("./config.js");

const connection = mysql.createConnection(config);

connection.connect((err) => {
  if (!err) {
    console.log("Connected to mySQL Database");
  } else {
    console.log("Connection Failed");
  }
});

const newTable = `CREATE TABLE IF NOT EXISTS details (
                    id int primary key auto_increment,
                    firstName varchar(50) NOT NULL,
                    lastName varchar(50) NOT NULL
                  )`;

connection.query(newTable, function (err, results, fields) {
  // console.log(results);
});

let firstName, lastName;

function insertEntry(firstName, lastName) {
  // firstName = "John";
  // lastName = "Doe";

  let newEntry = `INSERT INTO details (firstName, lastName)
                  VALUES ('${firstName}', '${lastName}')`;

  connection.query(newEntry, function (err, results, fields) {
    // console.log(results);
    if (!err) {
      console.log("Entry inserted into table");
    }
  });
}

// insertEntry();

You can use the http module on the server like this:

const http = require('http');

const server = http.createServer((req, res) => {
    if (req.method === 'POST') {
        //Notice we aren't handling routes here

        let body = '';
        req.on('data', chunk => {
            body += chunk.toString();
        });
        req.on('end', () => {
            //Finished receiving data

            body = JSON.parse(body)
            insertEntry(body.firstName, body.lastName)

            res.end('ok');
        });
    }
    else {
        if (req.url === '/'){
            //Serve index file
            fs.readFile("../views/index.php", function (err, data) {
                res.writeHead(200, { "Content-Type": "text/html" });
                res.write(data);
                return res.end();
            });
        } else {
            //Serve static content
            
            //This is dangerous because it allows reading any file like app.js
            //Note: remove the .. in the src and href in the php file, it looks cleaner this way
            fs.readFile('../' + req.url, (err, data) => {
                if (err){
                    res.statusCode = 404;
                    res.end('File not found');
                } else {
                    //Here we should parse the file name to determine the content type
                    //I'll leave that as an exercise to the reader
                    //Hint: https://stackoverflow.com/a/11972512/8891434

                    //res.setHeader('Content-Type', 'text/javascript')
                    
                    res.end(data)
                }
            })
        }
        res.end();
    }
});

server.listen(80);

And on the client I prefer to use the axios library

Add this inside the <head> to import it

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

And then you can send the data like this:

let firstName, lastName, response;

function submitDetails() {
  firstName = document.getElementById("inputFirstName").value;
  lastName = document.getElementById("inputLastName").value;

  response = confirm(`Please verify the submitted details.

  First Name: ${firstName}
  Last Name: ${lastName}`);

  if (response == true) {
    //Send data
    axios.post('your_backend_ip', {firstName: firstName, lastName: lastName}).then(() => {
       alert("Personal details submitted.");
    })
  } else {
    alert("You have cancelled your submission.");
  }
}

Of course, this is a very simple example since we don't handle multiple routes. I would recommend learning how to use the Express framework, it's easy to use and much more powerful than the http module.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM