我试图管理一个连接实例,使用一个函数来处理空闲连接断开问题,使用mysql数据库和node.js
目前,我已经获得了以下代码(coffescript):
mysql = require 'mysql'
handleDisconnect = () ->
connection = mysql.createConnection
host: 'localhost'
user: 'root'
password: 'passroot'
database: 'mydb'
connection.connect (err) ->
if err
console.log 'Error connecting to db: ', err
setTimeout handleDisconnect, 2000
connection.on 'error', (err) ->
console.log 'db error', err
if err.code == 'PROTOCOL_CONNECTION_LOST'
handleDisconnect()
else
throw err
handleDisconnect.instance = connection
module.exports = handleDisconnect
和
express = require 'express'
router = express.Router()
connection = require('../database')().instance
bcrypt = require 'bcryptjs'
router.post '/', (req, res) ->
credential = connection.escape req.body.credential
password = connection.escape req.body.password
res.send credential+password
module.exports = router
问题是,当我尝试访问路线时,出现以下错误:
无法阅读财产'逃避'未定义的
我做错了什么?
答案 0 :(得分:3)
我认为您的问题是handleDisconnect
的最后一行正在返回该实例,因此您尝试从instance
获取instance
,而不是{{1} }}。因此,如果要访问其中的属性,您将需要该函数在最后返回。
您还希望该功能使用等效的"此" (coffeescript中的handleDisconnect
)而不是具体指@
。
示例代码:
handleDisconnect
虽然我个人只是做了以下事情,但不要为"实例"而烦恼。在所有:
mysql = require 'mysql'
handleDisconnect = () ->
connection = mysql.createConnection
host: 'localhost'
user: 'root'
password: 'passroot'
database: 'mydb'
connection.connect (err) ->
if err
console.log 'Error connecting to db: ', err
setTimeout handleDisconnect, 2000
connection.on 'error', (err) ->
console.log 'db error', err
if err.code == 'PROTOCOL_CONNECTION_LOST'
handleDisconnect()
else
throw err
@instance = connection
@
module.exports = handleDisconnect
@connection
@instance = connection
。