簡體   English   中英

使用 node.js 和 JavaScript 從 HTML 簡單表單插入 INTO MySQL 表

[英]Insert INTO MySQL Table from HTML simple form using node.js and JavaScript

好吧,經過 3 天的努力,我被困在了一個讓我感到完全不知所措的地步。 我覺得自己就像一個迷失在 Web 開發這個巨大而未知的世界中的小孩(我是大型機開發人員),開始感到非常沮喪,所以我決定尋求認真的幫助。 我不會發布任何代碼,因為它在任何程度上都無濟於事。

我想要但仍然無法實現的:

  • 輸入“ localhost:8080/datos.html ”,其中有 2 個“文本框”和一個按鈕。 按下按鈕后,我希望使用 Node.js 將 2 個文本框(“名稱”和“密碼”)的數據存儲在 MySQL 數據庫中。

情況如下:

  • 我使用的是 Windows 7。
  • Node.js 安裝在我的 PC 上,我可以在 cmd 終端中執行“node server.js”,然后一切正常。
  • 我可以在'server.js'中,連接到MySQL數據庫並進行查詢,結果正常,我也可以進行插入,一切都很好。
  • 在同一個文件夾“ example.js ”文件中,我有一個名為“ datos.html ”的文件。
  • 使用“url解析”,我設法在瀏覽器(chrome)中寫入“localhost:8080/datos.html”,以便在啟動“服務器”后正確顯示“datos.html”(2文本框和按鈕顯示正確) .js' 通過 Node.js。

現在的問題開始:有根本沒有辦法,我可以設法插入在MySQL數據庫中的文本框的數據......正如我所說的,通過server.js插入數據是沒有問題的,既不是“讓”文本框的值與server.js 中的“document.getElementByI()”。 問題是,我找不到完成這個的方法 我知道這可能是一個蹩腳的問題,並且正在考慮不制作它,但是上帝,對於一個習慣了 COBOL、JCL 和 CICS 的人來說,Web 開發實在是太痛苦了。

作為參考,我從 W3Schools 中閱讀了有關 HTML、Ajax、Node.js 的“教程”和指南,可以執行其中顯示的示例,但無法鏈接這些內容以使所有內容成為單一功能的內容。

請注意,我的問題不是“技術”,我知道如何查詢 SQL 表,或“啟動”節點(以基本方式,tho),我知道如何制作(太)簡單的 HTML 並從node.js; 但問題是關於“如何做某事”,這很簡單,但我只是無法實現。

任何視頻、手冊、教程、課程或任何你必須幫助我實現這個簡單事情的東西,都會非常感激。

你走在正確的軌道上。 為了達到預期的目標,請執行以下操作。

1)您可以像Jason在上一個答案中提到的那樣使用express,現在將所有內容作為應用程序處理,客戶端和服務器在同一台機器上進行測試,就像我在我的應用程序中所做的那樣,直到您准備好將客戶端服務器與一台服務器分開其他。

2)為了使用 MySQL 作為存儲引擎而不是我使用的 SqlLite,請使用https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp 中的示例

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");
  var sql = "INSERT INTO customers (name, address) VALUES ('Company Inc', 'Highway 37')";
  con.query(sql, function (err, result) {
    if (err) throw err;
    console.log("1 record inserted");
  });
});

3)創建一個 HTML 文件來處理輸入,如下所示

4)創建一個client.js文件將請求發送到NodeJS服務器

5)創建 server.js 文件以接收請求並在我的情況下使用 SQLite 處理插入

6)為了創建數據庫,在故障控制台中運行以下命令

~sqlite demo      <---demo is name of db in sqlite3
% create table userlist(user, password);
CTRL+D            <---exit

7)找到一個合適的在線資源需要一些努力,但我找到了一個可以編輯 nodejs 項目以供查看的地方

我發現了這個: https : //flaviocopes.com/nodejs-hosting/並找到了一個名為 Glitch 的在線環境工具

試試我在 Glitch 構建的以下示例,一旦您單擊綠色的 Show Live 按鈕,就可以查看編輯並運行該示例。

https://glitch.com/edit/#!/node-js-demo-stack-overflow?path=public/client.js:1:0

客戶端.js

// client-side js
// run by the browser each time your view template referencing it is loaded

console.log('Testing Add');

function submit()
{
  // request the user from our app's sqlite database
  const userRequest = new XMLHttpRequest();
  userRequest.open('post', '/addUser');
  userRequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
  userRequest.send(JSON.stringify({'user':document.getElementById("user").value, 'password': document.getElementById("password").value}));
}

索引.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Welcome to Glitch!</title>
    <meta name="description" content="A cool thing made with Glitch">
    <link id="favicon" rel="icon" href="https://glitch.com/edit/favicon-app.ico" type="image/x-icon">
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- import the webpage's stylesheet -->
    <link rel="stylesheet" href="/style.css">
    
    <!-- import the webpage's client-side javascript file -->
    <script src="/client.js"></script>
  </head>
  <body>
    <input type="text" id="user"/>
    <input type="text" id="password"/> 
    <button onclick="submit()">Send</button>
  </body>
</html>

服務器.js

// server.js
// where your node app starts

// init project
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
//
// we've started you off with Express, 
// but feel free to use whatever libs or frameworks you'd like through `package.json`.

// http://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

// init sqlite db
var fs = require('fs');
var dbFile = 'demo';
var exists = fs.existsSync(dbFile);
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(dbFile);

// create application/json parser
var jsonParser = bodyParser.json();


// http://expressjs.com/en/starter/basic-routing.html
app.get('/', function(request, response) {
  response.sendFile(__dirname + '/views/index.html');
});

// endpoint to addUser in the database
// currently this is the only endpoint, ie. adding dreams won't update the database
// read the sqlite3 module docs and try to add your own! https://www.npmjs.com/package/sqlite3
app.post('/addUser', jsonParser, function(request, response) {
 
  
// if ./.data/sqlite.db does not exist, create it, otherwise print records to console
  if (!exists) {
    console.log("Table not found");
    db.run('CREATE TABLE userlist (user text, password text');
    console.log('New table User List Created!');
    insert(request);
  }
  else{
    insert(request);
  }
  db.each('SELECT * from userlist', function(err, row) {
      if ( row ) {
        console.log('record:', JSON.stringify(row));
      }
    });
});

var insert = function (req)
{
    db.run('INSERT INTO userlist (user, password) VALUES ("'+req.body.user+'","'+req.body.password+'")');
}
    
// listen for requests :)
var listener = app.listen(process.env.PORT, function() {
  console.log('Your app is listening on port ' + listener.address().port);
});

將此插入到 server.js 中的 post 處理程序的 else 塊中 insert(request) 下,以便能夠發回表值並在客戶端查看

db.all('SELECT * from userlist', function(err, rows) {
        response.send(rows);
    });

將此插入到 client.js 的提交函數中以查看提交時的表值

userRequest.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var rows = JSON.parse(this.responseText);
    var tbl = "<table border=1>";
    tbl += "<thead><td>Name</td><td>Password</td></thead>";
    for (var i = 0; i < rows.length; i++)
    {
      tbl+="<tr><td>"+rows[i].user+"</td><td>"+rows[i].password+"</td></tr>";
      console.log('record:', JSON.stringify(rows[i]));
    }
    tbl += "</table>";
    document.getElementById("tbl").innerHTML = tbl;
  }
}

如果您還沒有使用過,那么您可能應該使用 Node 框架作為傳入請求的路由器。 多年來最受歡迎的是 Express。

https://expressjs.com/

一旦你這樣做了,你就可以處理像這樣的請求

app.get("/datos", (req, res) => {
        // Serve the form logic here
    });

app.post("/datos", (req, res) => {
        // Handle the form submission logic here
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM