【问题标题】:Insert INTO MySQL Table from HTML simple form using node.js and JavaScript使用 node.js 和 JavaScript 从 HTML 简单表单插入 INTO MySQL 表
【发布时间】:2019-05-23 21:47:39
【问题描述】:

好的,经过 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 文本框和按钮显示正确)通过 Node.js 的“server.js”。

现在问题开始了:没有办法我可以设法将文本框的数据插入 MySQL 数据库...正如我所说,通过 server.js 插入数据不是问题,也不是从 server.js 中使用“document.getElementByI()”“获取”文本框值。问题是,我找不到方法来完成这个。 我知道这可能是一个蹩脚的问题,并且正在考虑不做,但是上帝,对于一个习惯于 COBOL、JCL 和 CICS 的人来说,Web 开发实在是太痛苦了。

作为参考,我阅读了来自 W3Schools 的关于 HTML、Ajax、Node.js 的“教程”和指南,可以执行其中显示的示例,但无法LINK 使所有内容都成为SINGLE 功能性的东西。

请注意,我的问题不是“技术”,我知道如何查询 SQL 表,或“启动”节点(以基本方式),我知道如何创建(也是)简单的 HTML 并从 node.js 显示它;但问题是关于“如何做某事”,这很简单,但我只是无法实现。

任何视频、手册、教程、课程或任何你必须帮助我完成这个简单事情的东西,都会非常感激。

【问题讨论】:

标签: javascript html mysql node.js


【解决方案1】:

你在正确的轨道上。为了达到预期的目标,请执行以下操作。

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

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

index.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>

server.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;
  }
}

【讨论】:

    【解决方案2】:

    如果您还没有,您可能应该使用 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
        });
    

    【讨论】:

      猜你喜欢
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 2020-02-26
      • 1970-01-01
      • 1970-01-01
      • 2020-03-25
      • 2015-05-21
      • 1970-01-01
      相关资源
      最近更新 更多