[英]How can I submit HTML form data into MySql database table using javascript along with node.js - mysql and without php?
[英]Insert INTO MySQL Table from HTML simple form using node.js and JavaScript
好吧,经过 3 天的努力,我被困在了一个让我感到完全不知所措的地步。 我觉得自己就像一个迷失在 Web 开发这个巨大而未知的世界中的小孩(我是大型机开发人员),开始感到非常沮丧,所以我决定寻求认真的帮助。 我不会发布任何代码,因为它在任何程度上都无济于事。
我想要但仍然无法实现的:
情况如下:
现在的问题开始:有根本没有办法,我可以设法插入在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。
一旦你这样做了,你就可以处理像这样的请求
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.