gpt4 book ai didi

javascript - RethinkDB,引用错误: connection is not defined

转载 作者:行者123 更新时间:2023-12-03 05:18:37 24 4
gpt4 key购买 nike

我正在使用 Express.jsRethink,我正在尝试对一条路线执行一个简单的 post 操作,将一些信息保存到初始连接工作正常并记录到控制台 Connected to Rethink 但是,当我尝试使用到 的连接时,我不断收到 ReferenceError:连接未定义 >插入一些东西。这是代码:

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");
}
});
}
dbConnect();

app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(session({secret: 'gitTy Up!',resave: false,saveUninitialized:true}));
app.use(require('connect-flash')());


app.set('view engine','ejs');

//Home Page
app.get('/', function (req, res) {
res.render('home');
})

app.get('/join', function (req, res) {
res.render('join');
})

app.post('/join',function(req, res){
var salt = bcrypt.genSaltSync(10);
r.table('users').insert([{email: req.body.email, password: bcrypt.hashSync(req.body.password, salt)}])
.run(connection, function(err,result) {
if (err) throw err;
console.log(JSON.stringify(result, null, 2));
})
});
app.listen(3000);

最佳答案

这是一个范围问题。连接的范围是本地的,您尝试像全局连接一样访问它。更改:

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");
}
});
}

关于javascript - RethinkDB,引用错误: connection is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com