我试过四处寻找,但无法真正找到我的问题的解决方案。要么,要么我并没有真正理解正确的东西。
我有一个带有简单表单的页面,该表单使用 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();
您可以像这样在服务器上使用 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] 删除。
我来说两句