gpt4 book ai didi

node.js - nodejs页面没有停止重新加载

转载 作者:太空宇宙 更新时间:2023-11-03 23:26:15 25 4
gpt4 key购买 nike

我创建了这段代码来使用nodejs和mysql将数据插入数据库这是有效的,数据已插入,但问题是,在我单击提交按钮并将相同的值多次发送到数据库后,页面仍然重新加载并且永远不会停止

服务器.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
bodyParser = require('body-parser');
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
database: 'chmult',
user: 'root',
password: '',
});
users = [];
connections = [];


app.get('/', function(req, res){
res.sendFile(__dirname + '/');

});



app.use(bodyParser.urlencoded({
extended: true
}));

/**bodyParser.json(options)
* Parses the text as JSON and exposes the resulting object on req.body.
*/
app.use(bodyParser.json());
connection.connect();

app.post("/", function (req, res) {
console.log(req.body.user.username)
connection.query("Insert into tesko (username) VALUES ('"+req.body.user.username+"')")



});



app.listen(3231);
console.log('Example app listening at port:3000');

html代码

<html>

<form method="post" action="">
<input type="text" name="user[username]">

<input type="submit" value="Submit">
</form>







</html>

最佳答案

您错过了 connection.query 上的回调,并且未对 res 执行任何操作

试试这个

app.post("/", function (req, res) {
console.log(req.body.user.username)
connection.query("INSERT INTO tesko (username) VALUES ('"+req.body.user.username+"')", function(err){
return res.send('Done');
})
});

看这里:

https://www.w3schools.com/nodejs/nodejs_mysql_insert.asp

正如问题评论中所述,SQL 注入(inject)已经成熟,您应该使用参数:

app.post("/", function (req, res) {
console.log(req.body.user.username)
connection.query("INSERT INTO tesko SET ? ", {username: req.body.username}, function(err){
return res.send('Done');
})
});

关于node.js - nodejs页面没有停止重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com