nodejs页面没有停止重新加载

时间:2017-05-09 22:19:18

标签: node.js

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

server.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>

1 个答案:

答案 0 :(得分:2)

您错过了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注入已经成熟,您应该使用参数:

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');
    })
});