Client.query not retrieving data in Node JS - javascript

I am working in a Web Application that connects to my PosgreSQL database, but when I go to the main page it suppose to retrieve the first element of the table actor, but is not retrieving anything, below my code. I checked the connection URL and is the correct username, password, port and database.
const express = require('express');
const bodyParser = require('body-parser');
const session = require("express-session");
const { Client } = require('pg');
const connectionString = 'postgres://postgres:12345#localhost:55306/dvdrental';
const cookieParser = require("cookie-parser");
const client = new Client({
connectionString: connectionString
});
client.connect();
const app = express();
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser("[mysecrethere]"));
app.use(session({
secret: "Dog",
resave: true,
saveUninitialized: true,
}));
app.get('/', function (req, res) {
client.query('SELECT * FROM actor', [1], function (err, result) {
if (err) {
console.log(err)
} else {
console.log(result);
}
});
});

You should finalize your middleware to return the data from database.
As an example, your code with minimal changes:
app.get('/', function (req, res) {
client.query('SELECT * FROM actor', [1], function (err, result) {
if (err) {
console.log(err)
return res.status(500).json(err.detail)
}
console.log(result);
res.status(200).json(result.rows)
});
});

Related

How to authenticate socket.io connection in nodejs application

I am working on a chat application where socket is used for bi-directional sharing of messages.
The socket currently works fine but I want to be able to authenticate user before they can have access to the socket connection. I have trying to use passport but it would seem there is something I am not doing right as I get the error No session found.
const createError = require("http-errors");
const express = require("express");
const { join } = require("path");
const logger = require("morgan");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const SequelizeStore = require("connect-session-sequelize")(session.Store);
const db = require("./db");
const { User } = require("./db/models");
const passport = require('passport');
// create store for sessions to persist in database
const sessionStore = new SequelizeStore({ db });
const http = require("http");
const db = require("../db");
const onlineUsers = require("../onlineUsers");
const passportSocketIo = require('passport.socketio');
const { json, urlencoded } = express;
const app = express();
app.use(logger("dev"));
app.use(json());
app.use(urlencoded({ extended: false }));
app.use(express.static(join(__dirname, "public")));
app.use(cookieParser());
app.use(session({
genid:(req)=>{
return req.cookies
},
secret: process.env.SESSION_SECRET,
resave: true,
store: sessionStore,
saveUninitialized: true,
}));
app.use(function (req, res, next) {
const token = req.cookies["messenger-token"];
if (token) {
jwt.verify(token, process.env.SESSION_SECRET, (err, decoded) => {
if (err) {
return next();
}
User.findOne({
where: { id: decoded.id },
}).then((user) => {
req.user = user;
return next();
});
});
} else {
return next();
}
});
app.use(passport.initialize());
app.use(passport.session());
const port = normalizePort(process.env.PORT || "3001");
app.set("port", port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces, and sync database.
*/
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST", "PUT"],
credentials: true
}
});
io.use(
passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'messenger-token',
secret: process.env.SESSION_SECRET,
store: sessionStore,
success: onAuthorizeSuccess,
fail: onAuthorizeFail
})
);
function onAuthorizeSuccess(data, accept) {
console.log('successful connection to socket.io');
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept) {
if (error) throw new Error(message);
console.log('failed connection to socket.io:', message);
accept(null, false);
}
io.on("connection", (socket) => {
// console.log(`USER ${JSON.stringify(socket)}`);
socket.on("go-online", (id) => {
if (!onlineUsers.includes(id)) {
onlineUsers.push(id);
}
// send the user who just went online to everyone else who is already online
socket.broadcast.emit("add-online-user", id);
});
socket.on("new-message", (data) => {
socket.broadcast.emit("new-message", {
message: data.message,
sender: data.sender,
});
});
socket.on("read-message", (data) => {
socket.broadcast.emit("read-message", data);
});
socket.on("read-messages", (data) => {
socket.broadcast.emit("read-messages", data);
});
socket.on("logout", (id) => {
if (onlineUsers.includes(id)) {
userIndex = onlineUsers.indexOf(id);
onlineUsers.splice(userIndex, 1);
socket.broadcast.emit("remove-offline-user", id);
}
});
});
How can I authenticate user with socket. Feel free to suggest other method aside using passport.
I found the same error in Github and it hasn't been resolved yet.
According to the official document (see "Compatibility with Express middleware" section), you can use express middleware in io.use by using wrap.
const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
The section shows how to use "express-session" module with socket.io. I guess this way is better for you because you already use it.

passport.initialize() middleware not in use

I am using node, express, mongoose and passport for my project and I implemented a simple Log In functionality to my code as seen below in app.js and it works perfectly. I then tried to split my code because I want to use MVC and this time when I run my application and try to log in I get the passport.initialize() middleware not in use Error. I have tried everything that other users in other posts have suggested but to no avail. Any suggestions?
app.js - old one which works
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const Donation = require('./models/Donation');
const User = require('./models/User');
const donationRoutes = require('./routes/donationRoutes');
const registerRoutes = require('./routes/registerRoutes');
// express app
const app = express();
// connect to mongodb & listen for requests
const dbURI = "mongodb+srv://test:test#test.8npff.mongodb.net/test?retryWrites=true&w=majority";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => app.listen(3000))
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
// express setup for login
const bodyParser = require('body-parser');
const expressSession = require('express-session')({
secret: 'secret',
resave: false,
saveUninitialized: false
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressSession);
// passport setup for auth login
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
// passport local authentification
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
/* LOGIN ROUTES */
const connectEnsureLogin = require('connect-ensure-login');
app.post('/login', (req, res, next) => {
passport.authenticate('local',
(err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
return res.redirect('/login?info=' + info);
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
return res.redirect('/');
});
})(req, res, next);
});
app.get('/login',
(req, res) => res.render('login', {title: 'login'})
);
app.get('/donations',
connectEnsureLogin.ensureLoggedIn(),
(req, res) => {
Donation.find().sort({ createdAt: -1 })
.then(result => {
res.render('donations/index', { donations: result, title: 'All Donations' });
})
.catch(err => {
console.log(err);
});
}
);
app.get('/user',
connectEnsureLogin.ensureLoggedIn(),
(req, res) => res.send({user: req.user})
);
app.get('/logout', function(req, res){
req.logout();
res.redirect('/');
});
//Register Routes
app.use('/', registerRoutes);
// *** routes ***
app.get('/', (req, res) => {
res.redirect('/donations');
});
//donation routes
app.use('/donations', donationRoutes);
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
app.js - new one
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const donationRoutes = require('./routes/donationRoutes');
const registerRoutes = require('./routes/registerRoutes');
const loginRoutes = require('./routes/loginRoutes');
// express app
const app = express();
// connect to mongodb & listen for requests
const dbURI = "mongodb+srv://test:test#test.8npff.mongodb.net/test?retryWrites=true&w=majority";
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then(result => app.listen(3000))
.catch(err => console.log(err));
// register view engine
app.set('view engine', 'ejs');
// middleware & static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
res.locals.path = req.path;
next();
});
//Register Routes
app.use('/', registerRoutes);
//Login Routes
app.use('/', loginRoutes);
// *** routes ***
app.get('/', (req, res) => {
res.redirect('/donations');
});
//donation routes
app.use('/donations', donationRoutes);
// 404 page
app.use((req, res) => {
res.status(404).render('404', { title: '404' });
});
loginController.js
const connectEnsureLogin = require('connect-ensure-login');
const Donation = require('../models/Donation');
const express = require('express');
const User = require('../models/User');
// express app
const app = express();
// express setup for login
const bodyParser = require('body-parser');
const expressSession = require('express-session')({
secret: 'secret',
resave: false,
saveUninitialized: false
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressSession);
// passport setup for auth login
const passport = require('passport');
app.use(passport.initialize());
app.use(passport.session());
// passport local authentification
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
const login_post = (req, res, next) => {
passport.authenticate('local',
(err, user, info) => {
if (err) {
return next(err);
}
if (!user) {
return res.redirect('/login?info=' + info);
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
return res.redirect('/');
});
})(req, res, next);
}
const login_get = (req, res) => {
res.render('login', {title: 'login'});
}
const index_get = (req, res) => {
connectEnsureLogin.ensureLoggedIn();
Donation.find().sort({ createdAt: -1 })
.then(result => {
res.render('donations/index', { donations: result, title: 'All Donations' });
})
.catch(err => {
console.log(err);
});
}
const user_get = (req, res) => {
connectEnsureLogin.ensureLoggedIn();
res.send({user: req.user});
}
const logout_get = (req, res) => {
req.logout();
res.redirect('/')
}
module.exports = {
login_post,
login_get,
index_get,
user_get,
logout_get
}
loginRoutes.js
const express = require('express');
const loginController = require('../controllers/loginController');
const router = express.Router();
router.post('/login', loginController.login_post);
router.get('/login', loginController.login_get);
router.get('/donations', loginController.index_get);
router.get('/user', loginController.user_get);
router.get('/logout', loginController.logout_get);
module.exports = router;
And here is the error log:
Error: passport.initialize() middleware not in use
at IncomingMessage.req.login.req.logIn (C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\node_modules\passport\lib\http\request.js:46:34)
at C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\controllers\loginController.js:43:9
at Strategy.strategy.success (C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\node_modules\passport\lib\middleware\authenticate.js:219:18)
at verified (C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\node_modules\passport-local\lib\strategy.js:83:10)
at C:\Users\123\Documents\Datenbanken_Projekt\transparent_blood\node_modules\passport-local-mongoose\index.js:205:41
There are two problems here:
You create new app more than once. First in app.js, then in loginController.js. You should use just one instance of app, otherwise it's like a second server and your middleware won't work properly.
In your example, you never initialize passport (using passport.initialize()). In the first sample (that is working), there are many lines of passport initialization, including strategies and stuff - everything after // passport setup for auth login. Then they're gone. You need to bring them back ;)

How to print out jwt token

I am trying to generate a jwt token and print it out by calling res.json() after the user has been authenticated, the problem is that I get the following error:
Cannot set headers after they are sent to the client
I tried solving the issue by using async and await but it still gives me the error. How can I res.json my token successfully?
Here is my node.js server:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const BASE_URL = process.env.BASE_URL;
const PORT = process.env.PORT || 1337;
const jwt = require('jsonwebtoken');
let Post = require('./models/post.model.js');
app.use(cors());
app.use("/assets", express.static(__dirname + "/assets"));
app.use(bodyParser.urlencoded({ extended: true }));
mongoose.connect(BASE_URL, { useNewUrlParser: true, useUnifiedTopology: true })
const connection = mongoose.connection;
connection.once('open', function () {
console.log('Connection to MongoDB established succesfully!');
});
app.set('view-engine', 'ejs');
app.get('/', (req, res) => {
res.render('index.ejs');
});
app.post('/', (req, res) => {
let username = req.body.username;
let password = req.body.password;
if (username !== process.env.USER_NAME && password !== process.env.USER_PASSWORD) {
res.json('Invalid credentials');
} else {
const token = jwt.sign({
username: username,
password: password
}, process.env.SECRET_KEY, {
expiresIn: '1h'
});
res.redirect('/dashboard');
res.json(token);
}
});
app.get('/dashboard', (req, res) => {
res.render('dashboard.ejs');
});
app.get('/dashboard/createPost', (req, res) => {
res.render('post.ejs');
});
app.post('/dashboard/createPost', async (req, res) => {
let collection = connection.collection(process.env.POSTS_WITH_TAGS);
res.setHeader('Content-Type', 'application/json');
let post = new Post(req.body);
collection.insertOne(post)
.then(post => {
res.redirect('/dashboard')
})
.catch(err => {
res.status(400).send(err);
});
});
app.listen(PORT);
You are calling res.redirect('/dashboard'); before the res.json(token);, you can't send a response twice that's why it's giving you the Cannot set headers after they are sent error.
What you can do instead is sending the token as a query via the redirect like this:
res.redirect(`/dashboard?token=${token}`);
Then you can get the token value from the front-end app by checking the query value.
Although this is not a very safe method

nodejs expressjs ERR_TOO_MANY_REDIRECTS

I have error with "ERR_TOO_MANY_REDIRECTS" in browser.
On linux server it looks like:
Error: Can't set headers after they are sent.
This is my app.js:
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();
const session = require('express-session');
const {getHomePage} = require('./routes/index');
const {getmain, addUserPage, addUser, deleteUser, editUser, editUserPage, addTemplates, getHistory} = require('./routes/user');
const port = 5000;
var auth = function(req, res, next) {
if (req.session && req.session.user === "amy" && req.session.admin)
return next();
else
return res.sendStatus(401);
};
// create connection to database
// the mysql.createConnection function takes in a configuration object which contains host, user, password and the database name.
const db = mysql.createConnection ({
host: 'localhost',
user: '*****',
password: '*****',
database: '*****',
charset : 'utf8mb4'
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
global.db = db;
// configure middleware
app.set('port', process.env.port || port); // set express to use this port
app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
app.set('view engine', 'ejs'); // configure template engine
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // parse form data client
app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
app.locals.moment = require('moment');
app.use(session({
secret: '2C44-4D44-WppQ38S',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 1800000}
}));
// routes for the app
app.get('/', getHomePage);
app.get('/main', auth, getmain);
app.get('/add', auth, addUserPage);
app.get('/edit/:id', auth, editUserPage);
app.get('/delete/:id', auth, deleteUser);
app.get('/addtemp/:login', auth, addTemplates);
app.get('/history', auth, getHistory)
app.post('/add', auth, addUser);
app.post('/edit/:id', auth, editUser);
app.post('/addtemp/:login', auth, addTemplates);
// Login endpoint
app.get('/login', function (req, res) {
if (!req.query.username || !req.query.password) {
res.send('login failed');
} else if(req.query.username === "amy" || req.query.password === "amy") {
req.session.user = "amy";
req.session.admin = true;
res.redirect('/main');
}
});
// Logout endpoint
app.get('/logout', function (req, res) {
req.session.destroy();
res.redirect("/");
});
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
I know I have some problems in
app.get('login...
Theres everything ok with success login using correct username and password but when I use incorrect nothing happend.
This is my module getmain (after correct login):
getmain: (req, res) => {
let query = "SELECT * FROM `users` ORDER BY id ASC";
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/main');
}
res.render('main.ejs', {
title: "blablabla"
,users: result
});
});
},
And this is index.js:
module.exports = {
getHomePage: (req, res) => {
let query = "SELECT * FROM `users` ORDER BY id ASC";
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/');
}
res.render('index.ejs', {
title: "blablabla"
,users: result
});
});
},
};
I read that's all because by looping but I can not figure it out.
I will be grateful for directing me to the source of the problem.

My route wont render

my studies/add wont render. I get "CastError: Cast to ObjectId failed for value "add" at path "_id" " error. I just dont get it, nothing seems to work the way I would expect. Im quite new to express. I tried all kind of different things but it just wont render /studies/add
my studies route `
const express = require('express')
const router = express.Router()
const Studies = require('../models/studies')
router.get('/', (req, res) => {
Studies.find({}, (err, studies) => {
studies.sort(function (a, b) {
return new Date(b.endDate) - new Date(a.endDate)
})
if (err) {
console.log(err)
} else {
res.render('studies', {
studies
})
}
})
})
router.get('/:id', function (req, res) {
Studies.findById(req.params.id, function (err, studies) {
if (err) {
console.log(err)
} else {
res.render('course', {
studies
})
}
})
})
router.get('/add', function (err, req, res) {
if (err) {
console.log(err)
}
res.render('addstudy')
})
module.exports = router
`
my app.js file
const express = require('express')
const bodyParser = require('body-parser')
const path = require('path')
const config = require('./config/database')
const mongoose = require('mongoose')
const Studies = require('./models/studies')
const session = require('express-session')
const passport = require('passport')
// const flash = require('connect-flash')
const app = express()
mongoose.connect(config.database)
let db = mongoose.connection
// Check connection
db.once('open', function () {
console.log('Connected to MongoDB')
})
// Check for DB errors
db.on('error', function (err) {
console.log(err)
})
const logger = function (req, res, next) {
console.log('loogging..')
next()
}
app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
// Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(logger)
// Passport Config
require('./config/passport')(passport)
// Passport Middleware
app.use(passport.initialize())
app.use(passport.session())
// Express Session Middleware
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}))
// Express Messages Middleware
/* app.use(require('connect-flash')())
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res)
next()
}) */
app.use(express.static('public'))
app.get('*', function (req, res, next) {
res.locals.user = req.user || null
next()
})
app.get('/', (req, res) => {
Studies.find({}, (err, studies) => {
console.log(studies)
if (err) {
console.log(err)
} else {
res.render('index', {
name: studies[0].name,
description: studies[0].description
})
}
})
})
let studies = require('./routes/studies')
let work = require('./routes/work')
let about = require('./routes/about')
let users = require('./routes/users')
app.use('/studies', studies)
app.use('/work', work)
app.use('/about', about)
app.use('/users', users)
app.listen(3002, () => {
console.log('started on 3002')
})

Categories