从NodeJS提交的数据在Mysql数据库中未定义

kd3sttzy  于 2023-08-02  发布在  Mysql
关注(0)|答案(2)|浏览(87)

当我提交表单数据时,数据添加到mysql数据库,值显示为未定义
有谁能告诉我是什么问题,我对NodeJs开发很陌生。
HTML文档

<html>

    <form method="post" action="/add">

    Name : <input   name="mname" type ="text" > <p>
    Age :  <input name="mage"   type ="text" > <p>
    Department : <input name="mdepartment"   type="text" > <p>
    City : <input   name="mcity" type = "text"> <p>

    <input type="submit" value ="submit">
    <input type="reset" value="reset"> 
    </form>
</center>

字符串
我的JavaScript文件如下
myapp.js

var express = require('express');
var path = require('path');
var mysql = require('mysql');
var app = express();
var bodyparser = require('body-parser');

var connection = mysql.createConnection({
    host : 'localhost',
    user : 'root',
    password : '1234'
});

connection.query('USE samplenodejs');

app.set('port',3000);

app.use(bodyparser.urlencoded({extended : false}));

app.get('/', function(req, res) {
    console.log('GET /');
    res.sendFile(__dirname + '/AddDetails.html');
});

app.post('/add',function(req,res){

connection.query("INSERT INTO test VALUES('','"+req.body.mname+"','"+req.body.mage+"','"+req.body.mcity+"','"+req.body.mdepartment+"')",function(err,res){
    if(err) throw err;
});
res.redirect('/');

});

app.listen(app.get('port'));
console.log('Express server listening on port '+app.get('port'));

o7jaxewo

o7jaxewo1#

我希望你能从客户端获得有效的数据。下面是插入数据的函数。Mysql字符串常量应该用"引号括起来。

app.post('/add',function(req,res){
    //Check this log in console, it should print all the values properly, if not issue is at clinet side
    console.log('Input:: name='+req.body.mname+' age='+ req.body.mage +' city='+ req.body.mcity + ' dep=' + req.body.mdepartment,   req.body);

    var Query = `INSERT INTO test (id, name, age, city, department) VALUES ("", "${req.body.mname}","${req.body.mage}","${req.body.mcity}","${req.body.mdepartment}" )`;

    //printing query in the console, if you still face the issue, you can execute this query manually.
    console.log("Query :" + Query );

    connection.query(Query, function(err,res){
        if(err) {
          console.error('Error in sql query:' + Query + ' Err', err);
          throw err;
        }
    });
    res.redirect('/');
});

字符串
不应该将用户输入直接传递给SQL查询,始终需要进行输入验证。
在NodeJs中,最好使用JSON key:value对进行插入,如下所示
connection.query('INSERT INTO test SET?',{name:req.body.mname,age:req.body. Mage },function(err,res){});

e5nqia27

e5nqia272#

问题肯定出在中间件主体解析器上。一旦重新检查中间件,并重新检查您发送到服务器的数据类型

相关问题