I am currently experimenting with passing queries from postgres database and loading it into a page. I have setup a test page with the following code below :
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;
However, when i run npm test, the stack trace is as follows:
/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)
Here is my part of my main app file
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;
What does the error refer to? Do i have to initialise pool in the app.js page in order to use it in routes?
if you are creating an object with your module Pool, it should be upper case.
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])
})
Related
I know that I am connecting to 'routes/dropbox' When I call the post inside the router, I get the error "Route.post() requires a callback function but got a [object Object]"
App.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var helmet = require('helmet');
var cors = require('cors');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var authRouter = require('./routes/auth');
var dbRouter = require('./routes/dropbox');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('combined'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(helmet());
app.use(cors());
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/auth', authRouter);
app.use('/db', dbRouter);
dropbox.js
You can see that I my app.post is set up inside router. The error is occurring when I call that post. Did I write this incorrectly?
var express = require('express');
var router = express.Router();
const dotenv = require('dotenv');
dotenv.config();
var app = express();
router.get('/getAllFolders', function (request, response, next)
{
app.post('https://api.dropboxapi.com/2/files/list_folder',
{
headers:
{
'Content-Type' : 'application/json',
'Authorization' : process.env.DB_AUTH
},
data:
{
'path': '',
'recursive': false,
'include_media_info': false,
'include_deleted': false,
'include_has_explicit_shared_members': false,
'include_mounted_folders': true,
'include_non_downloadable_files': false
}
})
.then(function (r)
{
res.send(r);
})
.catch(function (e)
{
res.send(e);
});
});
module.exports = router;
app is a local express instance. app.post is setting up a local handler for a post request, similar to router.post would.
Use a http client library like axios.
const axios = require('axios');
axios.post('https://api.dropboxapi.com/2/files/list_folder', data, options)
.then(function (r) {
res.send(r);
})
.catch(function (error) {
res.status(500);
res.send(error);
});
Hello I am getting an error when trying to start my server. This is what it says :
D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:139
debug('dispatching %s %s', req.method, req.url);
^
TypeError: Cannot read property 'method' of undefined
at Function.handle (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:139:34)
at router (D:\Other\Projects\Code\Powershell\shopping-cart\node_modules\express\lib\router\index.js:47:12)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\app.js:7:39)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Module.require (internal/modules/cjs/loader.js:1044:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (D:\Other\Projects\Code\Powershell\shopping-cart\bin\www:7:11)
at Module._compile (internal/modules/cjs/loader.js:1158:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
at Module.load (internal/modules/cjs/loader.js:1002:32)
at Function.Module._load (internal/modules/cjs/loader.js:901:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
My app.js file :
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var routes = require('./routes/index')(passport);
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var expressHbs = require('express-handlebars');
var mongoose =require('mongoose');
var app = express();
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var bodyParser = require('body-parser');
mongoose.connect('mongodb://localhost:27017/shopping', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.connection.on('error', err => {
throw 'failed to connect to MongoDB';
});
require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');
// view engine setup
app.engine('.hbs', expressHbs({defaultLayout: 'layout', extname:'.hbs'}))
app.set('view engine', '.hbs');
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({secret: 'mysupersecret', resave: false, saveUninitialized: false}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
And my index.js file :
var express = require('express');
var router = express.Router();
var Product = require('D:/Other/Projects/Code/Powershell/shopping-cart/models/product');
var csrf = require('csurf');
//var passport = require('D:/Other/Projects/Code/Powershell/shopping-cart/config/passport.js');
var passport = require ('passport');
var csrfProtection = csrf();
router.use(csrfProtection);
/* GET home page. */
router.get('/', function(req, res, next) {
Product.find(function(err, docs) {
var productChunks = [];
var chunkSize = 3;
for (var i = 0; i < docs.length; i += chunkSize) {
productChunks.push(docs.slice(i, i + chunkSize));
}
res.render('shop/index', { title: 'Shopping Cart', products: productChunks });
});
});
router.get('/user/signup', function (req, res, next) {
res.render('user/signup', {csrfToken: req.csrfToken()});
});
router.post('/user/signup', passport.authenticate('local.signup', {
successRedirect: '/user/profile',
failureRedirect: '/user/signup',
failureFlash: true
}));
router.get('/user/profile', function(req, res, next) {
res.render('user/profile');
});
module.exports = router;
Any hints on what could be the issue? I checked the lines that are being mentioned in the thrown error and can not find anything that is broken, and I have also checked other questions on this error, none that helped me. Any help is appreciated , thanks!
From the stack trace, it looks like the problem is caused by this line:
var routes = require('./routes/index')(passport);
If you look in your routes/index.js, you are exporting a router with:
module.exports = router;
Well, the problem is that you can't call router(passport). That's not a legit way to use a router. I can't tell what you were really trying to do with that. I would assume you want to hook your routes into the app with something like:
app.use(routes)
But, maybe you had some other intention there. In any case, router(passport) isn't something you can do.
FYI, it is a very useful skill to learn how to read these stack traces. You're typically looking to start at the top of the stack trace and go down line by line until you find a line of code that's in your own source file (your code that triggered this). Then, go examine that exact line with the context of what the eventual error was and see if you can then see what's wrong with that line of code or with the parameters used in that line of code.
i was learning how to make a login system with Express JS and a got that error in the Validator function and i don't know what's wrong with it nothing wrong with the syntax and it works in the tutorial that i am watching after serching in Github and other sites i found nothing and when i asked someone he told me something about NodeJs version but i am not sure about that, i don't know how to fix that.
This is my erorr:
//the erorr msg
erorrFormatter: fuction(param, msg, value){
^
SyntaxError: Unexpected token {
at new Script (vm.js:74:7)
at createScript (vm.js:246:10)
at Object.runInThisContext (vm.js:298:10)
at Module._compile (internal/modules/cjs/loader.js:670:28)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:713:10)
at Module.load (internal/modules/cjs/loader.js:612:32)
at tryModuleLoad (internal/modules/cjs/loader.js:551:12)
at Function.Module._load (internal/modules/cjs/loader.js:543:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:744:10)
at startup (internal/bootstrap/node.js:238:19)
Here is my code:
//my server code
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var expressValidator = require('express-validator');
var LocalStrategu = require('passport-local').Strategy;
var multer = require('multer');
var upload = multer({dest: './uploads'});
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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')));
//Handel sessions
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Validator
app.use(expressValidator({
erorrFormatter: fuction(param, msg, value){
var namespace = param.split('.');
var root = namespace.shift();
var formOaram = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return{
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Right, in your code you have the following;
erorrFormatter: fuction(param, msg, value){
There is a missing n in this, so replace with;
erorrFormatter: function(param, msg, value){
Simple typographical error in this instance, but adding the n should resolve pretty quickly
app js code
module.js:487
throw err;
^
Error: Cannot find module 'Handlebars'
at Function.Module._resolveFilename (module.js:485:15)
at Function.Module._load (module.js:437:25)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/app/routes/usersInfo.js:6:20)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
//global require extensions
const express = require('express');
const path = require('path');
//const hbs = require('Handlebars');
const exphbs = require('express-handlebars');
//var session = require('express-session');
const methodOverride = require('method-override');
const flash = require('connect-flash');
const session = require('express-session');
const bodyParser = require('body-parser');
const bcrypt = require('bcryptjs');
const passport = require('passport');
const mongoose = require('mongoose');
//const paginate = require('handlebars-paginate');
const app = express();
const email = require('email-validator');
var globals = require('globals'); //<< globals.js path
require('./models/User');
require('./models/Assignment')
require('./models/TimeSheet')
const User = mongoose.model('users')
const usersInfo = require('./routes/usersInfo');
const users = require('./routes/users');
const assignment = require('./routes/assignment');
const timesheet = require('./routes/timesheet');
require('./config/passport')(passport);
//db config
const db=require('./config/database');
mongoose.Promise = global.Promise;
global.autoincrement = 0;
//mongo connection
mongoose.connect('mongodb://venu:venu#ds117156.mlab.com:17156/tidrapportering',{useMongoClient:true})
.then(()=> console.log('MongoDB Connected..'))
.catch(err=>console.log(err));
const {ensureAuthenticated,select} = require('./helpers/auth');
//Load users model
//require('./models/Users');
//const User = mongoose.model('Users')
app.engine('handlebars',exphbs({ helpers: {
select:select
},defaultLayout:'main'}));
app.set('view engine','handlebars');
// Body parser middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Static folder
app.use(express.static(path.join(__dirname, 'public')));
// Method override middleware
app.use(methodOverride('_method'));
// Express session midleware
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// Global variables
app.use(function(req, res, next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
res.locals.accessadmin = false;
res.locals.accessuser = false;
res.locals.accessassistant =false;
res.locals.access = 'user';
res.locals.logout = false;
res.locals.user = req.user || null;
next();
});
app.get('/',(req, res)=>{
const title='Welcome2';
res.locals.logout = true;
User.findOne({email:'admin#simplegrowth.se'})
.then(user=>{
if(user){
req.flash('error_msg','');
res.redirect('/users/login');
}else{
const newUser=new User({
name :'Admin',
email: 'admin#simplegrowth.se',
password:'admin',
accesslevel: 'admin' });
bcrypt.genSalt(10,(err,salt)=>{
bcrypt.hash(newUser.password, salt,(err,hash)=>{
if(err) throw err;
newUser.password = hash;
newUser.save()
.then(user=>{
req.flash('success_msg', 'Admin created successfully.');
res.redirect('/users/login');
})
.catch(err=>{console.log(err);
return;
});
});
});
}
//res.render('index',{title:title});
});
});
app.get('/About',(req,res)=>{
res.render('About');
});
// have it listen on 8080
// Use routes
app.use('/users', users);
app.use('/usersInfo', usersInfo);
app.use('/assignment',assignment);
app.use('/timesheet',timesheet);
//app.use('/users', users);
const port = process.env.PORT||3443
app.listen(port,()=>{
console.log(`Server started on port ${port}`);
});
// this is only the app.js code but i am getting error while deploying in heroku and on click of open app in logs i am finding error mentioned above
Am trying to split and merge the uploaded pdf file in nodejs,while am running i getting error" TypeError: Cannot read property 'FileSystem' of undefined","ReferenceError: FS is not defined" help me to fix it.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var routes = require('./routes/index');
var users = require('./routes/users');
var gm = require('gm');
var app = express();
var fs =require('fs');
app.use(fileUpload());
app.post('/upload', function(req, res) {
var sampleFile;
console.log("upload");
if (!req.files) {
res.send('No files were uploaded.');
return;
}
new FS.Store.FileSystem("thumbs", {
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name() + '[0]').resize('100', '100').stream('png').pipe(writeStream);
},
beforeWrite: function (fileObj) {
return {
extension: 'pdf',
type: 'pdf'
};
},
path: "./public/images/",
})
sampleFile = req.files.sampleFile;
console.log("statrttttttttt");
console.log(req);
var fileName=sampleFile.name;
sampleFile.mv('./public/images/'+fileName, function(err) {
if (err) {
res.status(500).send(err);
}
else {
res.send("<html><h1><object data='/images/"+fileName+"'</h1></object></html>");
}
});
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/', routes);
app.use('/users', users);
module.exports = app;
new FS.Store.FileSystem("thumbs", {
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name() + '[0]').resize('100', '100').stream('png').pipe(writeStream);
},
javascript is case senesitive. you are referencing to fs module as:
var fs = require('fs');
and using FS.