我目前正在尝试从postgres数据库传递查询并将其加载到页面中。我用下面的代码设置了一个测试页面:
const sql_query = require('../sql');
var express = require('express');
var router = express.Router();
const { Pool } = require('pg')
const pool = new pool ({
connectionString: process.env.DATABASE_URL
});
pool.query('SELECT * FROM rides', [1], (err, res) => {
if (err) {
throw err
}
console.log('user:', res.rows[0])
})
module.exports = router;
但是,当我运行npm test时,堆栈跟踪如下:
/Users/lawjiahua/Desktop/CS2102_proj/App/routes/testPage.js:6
const pool = new pool ({
^
ReferenceError: Cannot access 'pool' before initialization
at Object.<anonymous> (/Users/lawjiahua/Desktop/CS2102_proj/App/routes/testPage.js:6:14)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
at Module.load (internal/modules/cjs/loader.js:798:32)
at Function.Module._load (internal/modules/cjs/loader.js:711:12)
at Module.require (internal/modules/cjs/loader.js:838:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/Users/lawjiahua/Desktop/CS2102_proj/App/app.js:25:22)
at Module._compile (internal/modules/cjs/loader.js:945:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:962:10)
这是我主应用程序文件的一部分
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
const pg = require('pg');
var app = express();
require('dotenv').config();
/* PAGES FOR THE PROJECT */
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var driverRouter = require('./routes/driver');
var awaitingApprovalRouter = require('./routes/awaitingApproval');
var registerDriverRouter = require('./routes/registerDriver');
var ridesRouter = require('./routes/rides');
var homepageRouter = require('./routes/homepage');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var testPageRouter = require('./routes/testPage');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
/* FOR PROJECT */
app.use('/', indexRouter);
app.use('/driver', driverRouter);
app.use('/awaitingApproval', awaitingApprovalRouter);
app.use('/registerDriver', registerDriverRouter);
app.use('/rides', ridesRouter);
app.use('/homepage', homepageRouter);
app.use('/testpage', testPageRouter);
module.exports = app;
该错误指的是什么?我是否必须在app.js页面中初始化池才能在路由中使用它?
答案 0 :(得分:1)
如果要使用模块Pool
创建对象,则该对象应为大写。
const { Pool } = require('pg')
const pool = new Pool ({
connectionString: process.env.DATABASE_URL
});
pool.query('SELECT * FROM rides', [1], (err, res) => {
if (err) {
throw err
}
console.log('user:', res.rows[0])
})