简体   繁体   中英

How to use express.js with mysql and express-myconnection?

I am using Express 4.9.0 and express-generator. Executed this command:

express --hbs projectname

Installed following modules with NPM:

  • mysql
  • express-myconnection

I want to make todo application. I have created separate file under routes/todo.js and created get/post routes for creating todos in that file using router.get and router.post .

i have following code in app.js:

// mysql connection
var connection = require('express-myconnection');
var mysql = require('mysql');

app.use(
    connection(mysql, {
        host : config.db.host,
        user : config.db.user,
        password : config.db.password,
        database : config.db.database,
        debug : false //set true if you wanna see debug logger
    }, 'request')
);
// end of mysql connection

Where should i place mysql config and connection code? Inside todo.js ? I still don't get concept of organisation file structure and where to place database queries.

I don't know if you eventually found the answer, but I thought it might help out others who accidentally stumbled on your question:

After you've setup like mentioned above, you can call the connection from the request object using the getConnection method like this:

exports.index = function(req, res) { 
    req.getConnection(function (err, connection) {
        connection.query('select * from table_name', function(err, rows, fields){
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.jsonp(rows);
            }
        });
    });
};

This should print out a json with the content of your table all nice an pretty. Hope this comes in handy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM