-1
我剛開始學用快遞的NodeJS framework.In我的應用程序有兩頁app.js和db.js..I需要從表單POST數據並插入到註冊表 在db.js如何連接mysql與nodejs?
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
請幫我.Thanks在advanc即
請參考[本](https://codeforgeek.com/2015/01/nodejs-mysql-tutorial/)..... –
假設該代碼的最高位是DB文件,那麼你調用你的MYSQL當你在應用程序中需要它時連接'db'。如果你把'var db = require('/ db');'改成'var connection = require('/ db');'那麼這可能會有所幫助。 – dan
@PunitGajjar:但我需要在db.js中定義連接以及如何訪問app.js中的頁面? –