你在正确的轨道上。为了达到预期的目标,请执行以下操作。
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;
}
}