[英]Do MySQL actions on call - Node.js
我一直在学习一些Node.js,并试图制作一个程序,在其中输入用户名和密码,并对照MySQL数据库进行检查。 我不知道我是否正确地完成了整个身份验证业务,但是我的问题是:在代码启动后(即在某种函数调用上)您可以调用MySQL函数吗?
您可以对函数调用执行MySQL操作吗?
我查看了互联网和其他有关Stack Overflow的问题,但我仍然不太了解。 我可能会错过有关Node.js实际功能的窍门。
这是我的代码:
HTML:
<html>
<head>
<title>Basic User Information</title>
</head>
<body>
<form action="http://localhost:8888/user" method="POST">
Username: <input type="text" name="username"> <br>
Password: <input type="text" name="password"> <br></select>
<input type="submit" value="submit">
</form>
</body>
</html>
Node.js的:
//import the express module
var express = require('express');
//import body-parser
var bodyParser = require('body-parser');
//store the express in a variable
var app = express();
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query("CREATE DATABASE authtest", function (err, result) {
if (err) throw err;
console.log("Database created");
});
con.query("CREATE TABLE users (username VARCHAR(255), password VARCHAR(255))", function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
//configure body-parser for express
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
//allow express to access our html (index.html) file
app.get('/index.html', function(req, res) {
res.sendFile(__dirname + "/" + "index.html");
});
//route the GET request to the specified path, "/user".
//This sends the user information to the path
app.post('/user', function(req, res){
response = {
username : req.body.username,
password : req.body.password
};
//this line is optional and will print the response on the command prompt
//It's useful so that we know what information is being transferred
//using the server
console.log(response);
//convert the response in JSON format
res.end(JSON.stringify(response));
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO users (username, password) VALUES (response.username, response.password)";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
});
//This piece of code creates the server
//and listens to the request at port 8888
//we are also generating a message once the
//server is created
var server = app.listen(8888, function(){
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
编辑:
我需要在另一个脚本中执行此操作吗? 那么,有一个用于页面初始化,一个用于将数据插入MySQL数据库?
据我所看到的代码,您正在通过表格传递的数据在users表中设置一个INSERT,并将服务器设置为在操作完成之前进行响应,因此该页面仍然可以接收到awnser,但是请回答您的问题YES ,您在节点服务器的“ index.js”中执行的操作将在启动后立即运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.