我正在使用Express.js
和Rethink
,我正在尝试对一条将一些信息保存到数据库的路由做一个简单的post
。初始连接正常工作并记录到然而,当我尝试使用与Connected to Rethink
的连接时,我一直收到ReferenceError: connection is not defined
。这是代码:
insert
答案 0 :(得分:1)
这是一个范围问题。连接在本地范围内,您尝试访问它,就像它是全局的一样。变化:
var express = require('express');
var app = express();
var r = require('rethinkdb');
var bodyParser = require('body-parser');
var session = require('express-session');
var bcrypt = require('bcryptjs');
function dbConnect(){
var connection = null;
r.connect({host: 'localhost', port: 28015}, function(err, conn){
if (err){
throw err;
}else{
connection = conn;
console.log("Connected to Rethink");
}
});
}`
到
var express = require('express');
var app = express();
var r = require('rethinkdb');
var bodyParser = require('body-parser');
var session = require('express-session');
var bcrypt = require('bcryptjs');
var connection = null;
function dbConnect(){
r.connect({host: 'localhost', port: 28015}, function(err, conn){
if (err){
throw err;
}else{
connection = conn;
console.log("Connected to Rethink");
}
});
}