[英]how to use async await on javascript frontend to receive data from async await node.js backend
[英]Integrating Frontend Javascript with Backend Node.Js and mySQL
我试过四处搜索,但无法真正找到解决我问题的方法。 要么,要么我没有真正正确地理解某些东西。
我有一个带有简单表单的页面,该表单使用 Javascript 在单击提交按钮时提醒用户他们的输入。 我还创建了一个 Node.Js function 以将输入插入 mySQL 数据库。 我不确定的是我是否能够在不使用像 Express Js 这样的框架的情况下将以上内容链接在一起。
我的代码如下:
index.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 模块功能强大得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.