如何将mysql与nodejs连接?

时间:2017-01-04 10:36:52

标签: mysql node.js

我刚开始用express framework学习nodejs。在我的应用程序中有两个页面app.js和db.js ..我需要从表单发布数据并插入到寄存器表 在db.js中

 var mysql = require('./node_modules/mysql');
    var connection = mysql.createConnection({
            host: '127.0.0.1',
            user: 'root',
            password: '',
            database: 'nodeapp'
        });
    connection.connect(function (err) {
        if (err)
            throw err;
    });
    module.exports = connection;

//在我的app.js页面

  var express = require('./lib/express');
    var app = express();
    var bodyParser = require('body-parser')
    var db = require('/db');
     app.get('/', function (req, res) {
        res.sendFile('/NodeProj/views/' + 'index.html');
    });
    /** bodyParser.urlencoded(options)
     * Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST)
     * and exposes the resulting object (containing the keys and values) on req.body
     */
    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());

    app.post('/process_form', function (req, res) {
        var response = {
            "firstname": req.body.fst_name,
            "email": req.body.fst_email,
            "password": req.body.fst_password
        };
        var query = connection.query('INSERT INTO register SET?',response,function(err,result){
            if(err) throw err;
            if(result) console.log(result);
        });
        res.end(JSON.stringify(response));
    });

    app.listen(8081);

但是当我运行代码时出现以下错误

Refference error: connection is not defined

请帮帮我。谢谢。

1 个答案:

答案 0 :(得分:1)

如评论中所述,您致电connection db

因此,如果您将var db = require('/db');替换为var connection = require('./db');,则会定义connection