TypeError:无法读取未定义的属性“查询”

时间:2019-08-07 08:37:44

标签: node.js

TypeError:无法读取未定义的属性“查询”

var express = require('express')
var app = express()

var mysql = require('mysql')

var myConnection  = require('express-myconnection')

var config = require('./config')
var dbOptions = {
    host:     config.database.host,
    user:     config.database.user,
    password: config.database.password,
    port:     config.database.port, 
    database: config.database.db
}

app.use(myConnection(mysql, dbOptions, 'pool'))

app.set('view engine', 'ejs')

var index = require('./routes/index')
var users = require('./routes/users')

var expressValidator = require('express-validator')
app.use(expressValidator())


var bodyParser = require('body-parser')

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

var methodOverride = require('method-override')

app.use(methodOverride(function (req, res) {
  if (req.body && typeof req.body === 'object' && '_method' in req.body) {
    // look in urlencoded POST bodies and delete it
    var method = req.body._method
    delete req.body._method
    return method
  }
}))

var flash = require('express-flash')
var cookieParser = require('cookie-parser');
var session = require('express-session');

app.use(cookieParser('keyboard cat'))
app.use(session({ 
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: { maxAge: 60000 }
}))
app.use(flash())


app.use('/', index)
app.use('/users', users)

app.listen(3000, function(){
    console.log('Server running at port 3000: http://127.0.0.1:3000')
})

这是我的Users.js。

    var express = require('express')
    var app = express()

    // ADD NEW USER POST ACTION
app.post('/add', function(req, res, next){  
    req.assert('name', 'Name is required').notEmpty()           //Validate name
    req.assert('age', 'Age is required').notEmpty()             //Validate age
    req.assert('email', 'A valid email is required').isEmail()  //Validate email

    var errors = req.validationErrors()

    if( !errors ) {   //No errors were found.  Passed Validation!

        /********************************************
         * Express-validator module

        req.body.comment = 'a <span>comment</span>';
        req.body.username = '   a user    ';

        req.sanitize('comment').escape(); // returns 'a &lt;span&gt;comment&lt;/span&gt;'
        req.sanitize('username').trim(); // returns 'a user'
        ********************************************/
        var user = {
            name: req.sanitize('name').escape().trim(),
            age: req.sanitize('age').escape().trim(),
            email: req.sanitize('email').escape().trim()
        }

        req.getConnection(function(error, conn) {
            conn.query('INSERT INTO users SET ?', user, function(err, result) {
                //if(err) throw err
                if (err) {
                    req.flash('error', err)

                    // render to views/user/add.ejs
                    res.render('user/add', {
                        title: 'Add New User',
                        name: user.name,
                        age: user.age,
                        email: user.email                   
                    })
                } else {                
                    req.flash('success', 'Data added successfully!')

                    // render to views/user/add.ejs
                    res.render('user/add', {
                        title: 'Add New User',
                        name: '',
                        age: '',
                        email: ''                   
                    })
                }
            })
        })
    }
    else {   //Display errors to user
        var error_msg = ''
        errors.forEach(function(error) {
            error_msg += error.msg + '<br>'
        })              
        req.flash('error', error_msg)       


        res.render('user/add', { 
            title: 'Add New User',
            name: req.body.name,
            age: req.body.age,
            email: req.body.email
        })
    }
})

Here is the error i got it on the terminal

我正在学习node.js,并且想要执行CRUD操作。我正在使用mysql db。现在,插入记录时的问题是它没有读取查询的属性。

我想在数据库中添加数据。但是我得到的实际结果是TypeError:无法读取未定义的属性“查询”

3 个答案:

答案 0 :(得分:3)

在聊天中与@Orion讨论后,我们发现真正的错误是

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

因此解决方案是重新安装XAMPP

答案 1 :(得分:2)

请打印从req.getConnection(function(error, conn) {返回的错误。 SQL连接中似乎有一个错误,因此它不返回任何conn对象。如果错误不为空,请不要执行SQL查询。

if(error == null){
   //EXECUTE QUERIES
}else{
   console.log(error)
   //RETURN ERROR   
}

是一个免费的建议:当您学习新事物时,不必处理太多软件包,这会使您的学习变得复杂。

答案 2 :(得分:0)

请参阅

config.js

const HOST = 'hostnname'
const USER = 'username'
const PASSWORD = 'password'
const DB_NAME = 'databasename'



module.exports = {
    connectionLimit: 1,
    host: HOST,
    user: USER,
    password: PASSWORD,
    database: DB_NAME
}

user.js

var mysql = require('mysql');

var config = require('./config');

var connection = mysql.createPool(config);

exports.authentication = (req, res) => {


    if (req.method === 'OPTIONS') {
        console.log('!OPTIONS');
        res.end();
    } else {

            res.set("Access-Control-Allow-Origin", "*");
            res.set("Access-Control-Allow-Methods", "POST");
            res.set("Access-Control-Allow-Headers", "Content-Type");
            var userQuery = 'INSERT INTO users SET ? '
            pool.query(userQuery, [user])
            .then(results => {
                  res.status(200).send(results);

                } else {
                    next();
                }
            })
            .catch(err => {
                reject(err);
            })

    }
};