将前端 Javascript 与后端 Node.Js 和 mySQL 集成

佐提乌斯

我试过四处寻找,但无法真正找到我的问题的解决方案。要么,要么我并没有真正理解正确的东西。

我有一个带有简单表单的页面,该表单使用 Javascript 在单击提交按钮时提醒用户他们的输入。我还创建了一个 Node.Js 函数来将输入插入到 mySQL 数据库中。我不确定是否能够在不使用 Express Js 之类的框架的情况下将上述内容链接在一起。

我的代码如下:

索引.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>

表单.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.");
  }
}

应用程序.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");
});

配置.js

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

module.exports = config;

我的文件夹树是这样的:

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

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

使用 Fedex7501 的答案更新:

应用程序.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();
联邦快递7501

您可以像这样在服务器上使用 http 模块:

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);

在客户端我更喜欢使用 axios 库

在 <head> 中添加它以导入它

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

然后你可以像这样发送数据:

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.");
  }
}

当然,这是一个非常简单的例子,因为我们不处理多条路由。我建议学习如何使用 Express 框架,它易于使用并且比 http 模块更强大。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何集成Golang后端和Javascript(three.js)前端?

将前端文件HTML,CSS和JS链接到后端node.js

将后端集成到前端

如何将Google oAuth与Node.js后端和Angular前端一起使用?

无法在 Express、Node 和 Javascript 中连接前端和后端

Vue.js和Node.js-我应该将图像上传到vue(前端)还是节点(后端)

将JavaScript接口与Rails后端集成

如何集成oauth以响应前端和节点后端?

使用React和axios前端连接到我的Node.js和MongoDB后端的问题

如何在服务器上部署Node Js后端和React Js前端?

ejabberd 和后端集成

在GatsbyJS中将视频显示为前端,将Node js显示为后端以及将mysql用于数据库的最佳方法

(设计问题)如何解耦前端和后端以保护路由(后端)代码?(Node.js-快速-反应)

桥接Python后端和JavaScript前端

Vue前端烧瓶后端集成

为Vue应用程序前端和node.js后端配置Nginx

React / Redux前端和Node.js后端之间的CORS问题

如何在node.js中组织前端和后端项目结构?

如何正确地在前端和 node.js 后端之间发送 firebase auth tokenId

NGinx 不在 Node.js 后端和 React 前端之间路由

将jBPM与Node.js和PostgreSQL集成

如何在 javascript 前端使用 async await 从 async await node.js 后端接收数据

在后端使用已经编写的前端javascript与node.js可行吗?

将Nuxt前端与Flask后端集成的最佳方法

Nextjs 将前端和后端的流程分开

无法通过我的前端从我的 node js 服务器下载图像文件(我的后端和前端是解耦的)

将Vue js前端和laravel后端(API路由)托管到共享服务器?

Node JS Express用于后端,React JS用于前端

如何在单个 Heroku 应用程序中部署前端(React.js)和后端(Node.js)