2017-05-09 10 views
1

nodejsとmysqlを使用してデータベースにデータを挿入するためにこのコードを作成しましたが、それは機能し、データは挿入されましたが、ページはまだリロードされ、データベースに同じ値を複数回nodejsページが再ロードを停止していません

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> 
+2

ユーザー入力をSQLクエリーに盲目的に連結して、注入攻撃を求めています。 **これをしないでください** – mscdex

答えて

2

あなたはMISSEをしましたD connection.query上のコールバックとあなたはここを参照してください。この

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

を試してみてくださいres

で何もしない:

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

w3schoolsを参照することは避けてください(何でも)。代わりに、関連する公式文書[here](https://github.com/mysqljs/mysql/blob/master/Readme.md)を参照してください。 – mscdex

+0

私は持っていましたが、残念なことに* official * docsのどこにも、OPが達成しようとしているものの明確かつ簡潔な例はありません。 – Alex

関連する問題