I use node js and socket io on my website and i have a problem, i want to connect my client on my website when my "client.on('Connexion', function(data) { } " is called, and i have a problem :
/* ------- CALLBACK CONNECTION : --------*/
io.sockets.on('connection', function (client, req, res) {
client.on('Connexion', function(data) {
blabla...
if(results[0]) {
req.session.id = results[0];
req.session.firstname = results[1];
req.session.lastname = results[2];
req.session.email = results[4];
req.session.birthdate = results[5];
req.session.phonenum = results[6];
res.redirect("http://mydomain/" + "espace-client/");
/* HERE, req.session give and error --> TypeError: Cannot read property 'session' of undefined */
}
}
});
/* ------- I HAVE TEST THIS AND IT WORKS FINE : --------*/
app.get('/test/', function(req, res) {
req.session.id = "45";
res.send(req.session.id);
});
Thank you in advance :)
You can try to do this:
const io = socketIO.listen(server);
io.sockets
.on('connection', socket => {
socket.on('socket.setOnline', async event => {
const { access_token } = event;
if (!access_token) return socket.emit('socket.error', 'no access_token token');
jwt.verify(access_token, 'HelloThere', err => {
if (err) socket.emit('socket.error', err.message);
});
const user = await userService.getByAccessToken(access_token);
if (!user) return socket.emit('socket.error', 'user on setOnline not found');
user.update({ isOnline: true });
socket.emit('socket.notification', `#${user.id}: ${user.name} is online`);
socket.emit('socket.userStatus', { status: 'online' })
})
socket.on('socket.setOffline', async event => {
const { access_token } = event;
if (!access_token) return socket.emit('socket.error', 'no access_token token');
jwt.verify(access_token, 'HelloThere', err => {
if (err) socket.emit('socket.error', err.message)
});
const user = await userService.getByAccessToken(access_token);
if (!user) return socket.emit('socket.error', 'user on setOffline not found');
user.update({ isOnline: false });
socket.emit('socket.notification', `#${user.id}: ${user.name} is offline`);
socket.emit('socket.userStatus', { status: 'offline' })
})
socket.on('socket.checkUserStatus', async event => {
const { access_token } = event;
if (!access_token) return socket.emit('socket.error', 'no access_token token');
jwt.verify(access_token, 'HelloThere', err => {
if (err) socket.emit('socket.error', err.message);
});
const user = await userService.getByAccessToken(access_token);
socket.emit('socket.userStatus', { status: user.isOnline ? 'online' : 'offline' })
})
})
Related
When I run yarn build, everything works fine but, when I run yarn start, I get the following error in terminal -
$ NODE_ENV=production node ./dist/server.generated.js
/home/prithvi/Desktop/Socialize-app/node_modules/express/lib/router/route.js:202
throw new Error(msg);
^
Error: Route.put() requires a callback function but got a [object Undefined]
at Route.<computed> [as put] (/home/prithvi/Desktop/Socialize-app/node_modules/express/lib/router/route.js:202:15)
at Object.9816 (/home/prithvi/Desktop/Socialize-app/dist/server.generated.js:1:71630)
at o (/home/prithvi/Desktop/Socialize-app/dist/server.generated.js:1:77368)
at Object.642 (/home/prithvi/Desktop/Socialize-app/dist/server.generated.js:1:63316)
at o (/home/prithvi/Desktop/Socialize-app/dist/server.generated.js:1:77368)
at /home/prithvi/Desktop/Socialize-app/dist/server.generated.js:1:78149
at /home/prithvi/Desktop/Socialize-app/dist/server.generated.js:1:78597
at Object.<anonymous> (/home/prithvi/Desktop/Socialize-app/dist/server.generated.js:1:78618)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:816:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47
error Command failed with exit code 1.
Below is the route file i.e.,
post.routes.js
import express from 'express';
import UserCtrl from '../controllers/user.controller';
import authCtrl from '../controllers/auth.controller';
import postCtrl from '../controllers/post.controller';
const router = express.Router();
router
.route('/api/posts/new:userId')
.post(authCtrl.requireSignin, postCtrl.create);
router.route('/api/posts/photo/:postId').get(postCtrl.photo);
router
.route('/api/posts/by/:userId')
.get(authCtrl.requireSignin, postCtrl.listByUser);
router
.route('/api/posts/feed/:userId')
.get(authCtrl.requireSignin, postCtrl.listNewsFeed);
router.route('/api/posts/like').put(authCtrl.requireSignin, postCtrl.like);
router.route('/api/posts/unlike').put(authCtrl.requireSignin, postCtrl.unlike);
router
.route('/api/posts/comment')
.put(authCtrl.requireSignin, postCtrl.comment);
router
.route('/api/posts/uncomment')
.put(authCtrl.requireSignin, postCtrl.uncomment);
router
.route('/api/posts/:postId')
.delete(authCtrl.requireSignin, postCtrl.isPoster, postCtrl.remove);
router.param('userId', UserCtrl.userById);
router.param('postId', postCtrl.postById);
export default router;
Here's the controller file i.e.,
post.controller.js
import Post from '../models/post.model';
import errorHandler from './../helpers/dbErrorHandler';
import formidable from 'formidable';
import fs from 'fs';
const create = (req, res, next) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, async (error, fields, files) => {
if (error) {
return res.status(400).json({
error: 'Image could not be uploaded',
});
}
let post = new Post(fields);
post.postedBy = req.profile;
if (files.photo) {
post.photo.data = fs.readFileSync(files.photo.path);
post.photo.contentType = files.photo.type;
}
try {
let result = await post.save();
res.json(result);
} catch (error) {
return res.status(400).json({
error: errorHandler.getErrorMessage(error),
});
}
console.log(error);
});
};
const postById = async (req, res, next, id) => {
try {
let post = await Post.findById(id).populate('postedBy', '_id.name').exec();
if (!post) {
return res.status(404).json({
error: 'Post not found',
});
}
req.post = post;
next();
} catch (error) {
return res.status(400).json({
error: "Couldn't retrieve the user post",
});
}
};
const listByUser = async (req, res) => {
try {
let posts = await Post.find({ postedBy: req.profile._id })
.populate('comments.postedBy', '_id name')
.populate('postedBy', '_id name')
.sort('-created')
.exec();
res.json(posts);
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err),
});
}
};
const listNewsFeed = async (req, res) => {
let following = req.profile.following;
following.push(req.profile._id);
try {
let posts = await Post.find({ postedBy: { $in: req.profile.following } })
.populate('comments.postedBy', '_id name')
.populate('postedBy', '_id name')
.sort('-created')
.exec();
res.json(posts);
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err),
});
}
};
const remove = async (req, res) => {
let post = req.post;
try {
let deletedPost = await post.remove();
res.json(deletedPost);
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err),
});
}
};
const photo = (req, res, next) => {
res.set('Content-Type', req.post.photo.contentType);
return res.send(req.post.photo.data);
};
const like = async (req, res) => {
try {
let result = await Post.findByIdAndUpdate(
req.body.postId,
{ $push: { likes: req.body.userId } },
{ new: true }
);
res.json(result);
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err),
});
}
};
const unlike = async (req, res) => {
try {
let result = await Post.findByIdAndUpdate(
req.body.postId,
{ $pull: { likes: req.body.userId } },
{ new: true }
);
res.json(result);
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err),
});
}
};
const comment = async (req, res) => {
let comment = req.body.comment;
comment.postedBy = req.body.userId;
try {
let result = await Post.findByIdAndUpdate(
req.body.postId,
{ $push: { comments: comment } },
{ new: true }
)
.populate('comments.postedBy', '_id name')
.populate('postedBy', '_id name')
.exec();
res.json(result);
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err),
});
}
};
const uncomment = async (req, res) => {
let comment = req.body.comment;
try {
let result = await Post.findByIdAndUpdate(
req.body.postId,
{ $pull: { comments: { _id: comment._id } } },
{ new: true }
)
.populate('comments.postedBy', '_id name')
.populate('postedBy', '_id name')
.exec();
res.json(result);
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err),
});
}
};
// Used to authenticate user to verify if the user who
// posted is same as the user who is deleting it.
const isPoster = (req, res, next) => {
let isPoster = req.post && req.auth && req.post.postedBy._id == req.auth._id;
if (!isPoster) {
return res.status('403').json({
error: 'User is not authorized',
});
}
next();
};
export default {
listByUser,
listNewsFeed,
create,
postById,
remove,
photo,
like,
unlike,
comment,
uncomment,
isPoster,
};
The versions of modules I used are -
express#4.17.1
nodemon#2.0.7
webpack#5.24.4
What can be the reason for that error ?
I am having a flow of registering a new user.
I am getting the error UnhandledPromiseRejectionWarning: TypeError: createUser is not a function
auth.js
const express = require("express");
const authrequests = express.Router();
const cors = require("cors");
var createUser = require("./export/authConstants");
// Register User
authrequests.post("/register", async (req, res) => {
const userData = {
firstname: req.body.firstname,
lastname: req.body.lastname,
email: req.body.email,
phone: req.body.phone,
password: req.body.password,
created: new Date(),
};
await createUser(userData)
.then((res) => {
console.log(res)
if (res.status == 200) {
return res.status(200).json({ msg: 'Registered!' });
} else if (res.status == 405) {
return res.status(405).json({ error: 'User already exists' });
} else {
return res.status(400).json({ error: err });
}
})
.catch(err => {
return res.status(400).json({ error: err });
})
});
module.exports = authrequests;
authConstants.js
const customers = require("./../../models/customers");
var hashPassword = require("./util/bcrypt");
var jwtCreate = require("./util/jwt");
var sendMail = require("./util/mail");
var BASE_URL = require("./../constants/constants");
//register
createUser = (userData) => {
return new Promise(async (resolve, reject) => {
customers.findOne({ where: { email: userData.email } })
.then(async (user) => {
if (!user) {
var hashResponse = await hashPassword(userData.password)
if (hashResponse.msg) {
userData.password = hashResponse.msg
customers.create(userData)
.then(async (user) => {
if (user) {
var jwtResponse = await jwtCreate({ data: user.id, expiry: 172800 })
if (jwtResponse.msg) {
const url = `${BASE_URL}/auth/emailVerified/${jwtResponse.msg}`;
var mailResponse = await sendMail({
to: user.email,
subject: 'Email Verification',
html: `Click on the following link to verify your account: click here`
})
if (mailResponse.msg) {
resolve({ status: 200 })
} else {
reject({ error: mailResponse.err })
}
} else {
reject({ error: jwtResponse.err })
}
} else {
reject({ error: "oops..! user creation failed" })
}
})
.catch(err => {
reject({ error: err })
});
} else {
reject({ error: hashResponse.err })
}
} else {
resolve({ status: 405 })
}
})
.catch(err => {
reject({ error: err })
})
})
};
bcrypt.js
const bcrypt = require("bcrypt");
//hashing password
hashPassword = async (password) => {
await bcrypt.hash(password, 10, (err, hash) => {
if (hash) {
return { msg: hash };
} else {
return { error: err };
}
})
};
jwt.js
const jwt = require("jsonwebtoken");
var EMAIL_SECRET = require("./../../constants/constants");
//jwt creation
jwtCreate = async (data) => {
await jwt.sign(data.data, EMAIL_SECRET, { expiresIn: data.expiry }, (err, token) => {
if (token) {
return { msg: token };
} else {
return { error: err };
}
})
};
mail.js
const nodemailer = require("nodemailer");
var MAIL_HOST = require("./../../constants/constants");
var EMAIL_USER = require("./../../constants/constants");
var EMAIL_PASS = require("./../../constants/constants");
//mail send
sendMail = async (data) => {
let transporter = nodemailer.createTransport({
host: MAIL_HOST,
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: EMAIL_USER,
pass: EMAIL_PASS,
},
tls: {
rejectUnauthorized: false,
},
});
await transporter.sendMail({
from: EMAIL_USER,
to: data.to,
subject: data.subject,
html: data.html
}, (err, response) => {
if (token) {
return { msg: response };
} else {
return { error: err };
}
});
};
constants.js
const EMAIL_SECRET = "asdf1093KMnHGcvnkljvasdu09123nlasdasdf";
const MAIL_HOST = "mail.test.com";
const EMAIL_USER = "no_reply_auth#test.com";
const EMAIL_PASS = "JMkC+)*Lv";
const BASE_URL = "http://localhost:3001";
UnhandledPromiseRejectionWarning: TypeError: createUser is not a function
is there something I am missing out..? or the entire flow is wrong..?
I'm trying to make get request via token from local storage but it is giving me Request aborted error.
Here is My nodeJS code :
//Read
app.get('/:username',verify, (req, res) => {
console.log('Welcome to roffys server')
Todo.find({'username' : req.params.username})
.exec((err, todo) => {
if (err) {
console.log('Error retrieving todos')
} else {
res.json(todo)
}
})
})
Here is the Verify function :
const jwt = require('jsonwebtoken')
module.exports = function (req,res,next){
const token = req.header('Authentication')
if(!token) return res.status(401).send('Access Denied')
try {
const verified = jwt.verify(token, 'secretkey')
req.user = verified
}catch (err) {
res.status(400).send(
'Invalid token'
)
next()
}
And here is my FE on ReactJS component:
componentDidMount() {
axios
.get(`http://localhost:8080/${localStorage.getItem('username')}`,{
headers : {
Authentication : localStorage.getItem('token')
}
})
.then((res) => {
this.setState({todos: res.data})
this.setPageCount()
})
.catch((err) => {
console.log("err", err);
});
}
None of yow methods return anything.
componentDidMout () {
return axios.get(url, config)
.then (res=> this.setState(myProp: res.data});
......
Back
var verify = require(“./path/to verify”);
//Read
app.get('/:username',verify, (req, res) => {
return Todo.find({'username' : req.params.username})
.exec()
.then(todo=> res.json(todo))
.catch(console.log);
})
I am working on a 'change password' functionality. I am starting to learn more about Promises and have the following code:
router.post('/change-password', verifyToken, csrfProtection, (req, res, next) => {
if (!req.body.password_current || !req.body.password_new) {
req.flash('info', 'Please fill in both fields.');
return res.redirect('/change-password');
}
const data = {};
data.password = req.body.password_new;
tokenHandler.verifyToken(req.cookies.token)
.then((decoded) => {
return User.findOne({ '_id.user_id': decoded.user });
})
.then((user) => {
data.userId = ObjectId(user._id.user_id);
return bcrypt.compare(req.body.password_current, user.password);
})
.then((allowed) => {
if (!allowed) {
return res.redirect('/change-password');
}
console.log('I am not here');
return User.findOneAndUpdate({ '_id.user_id': data.userId }, { password: data.password }, { new: true });
})
.then(() => {
return res.redirect('/change-password');
})
.catch((err) => {
return next(err);
});
});
I love how Promises are preventing the 'callback hell'. The problem is that I am receiving a 'headers already sent' error. I know that is because I can't escape the chain and that it saves up all the results (unless you throw an Error). To fix the problem I used the following:
router.post('/change-password', verifyToken, csrfProtection, (req, res, next) => {
if (!req.body.password_current || !req.body.password_new) {
req.flash('info', 'Please fill in both fields.');
return res.redirect('/change-password');
}
const data = {};
data.password = req.body.password_new;
tokenHandler.verifyToken(req.cookies.token)
.then((decoded) => {
User.findOne({ '_id.user_id': decoded.user }).then((user) => {
data.userId = ObjectId(user._id.user_id);
bcrypt.compare(req.body.password_current, user.password).then((allowed) => {
if (!allowed) {
return res.redirect('/change-password');
}
User.findOneAndUpdate({ '_id.user_id': data.userId }, { password: data.password }).then((doc) => {
console.log(doc);
return res.redirect('/change-password');
});
});
});
});
});
The question is: Is there a better solution to fix the 'header already sent' error. Because I have the feeling that my solution is actually a few steps away from a 'callback hell' structure.
You can rewrite it like this
router.post('/change-password', verifyToken, csrfProtection, (req, res, next) => {
if (!req.body.password_current || !req.body.password_new) {
req.flash('info', 'Please fill in both fields.');
return res.redirect('/change-password');
}
const data = {};
data.password = req.body.password_new;
tokenHandler.verifyToken(req.cookies.token)
.then((decoded) => {
return User.findOne({ '_id.user_id': decoded.user });
})
.then((user) => {
data.userId = ObjectId(user._id.user_id);
return bcrypt.compare(req.body.password_current, user.password);
})
.then((allowed) => {
if (!allowed) {
return res.redirect('/change-password');
}
else{
console.log('I am not here');
return User.findOneAndUpdate({ '_id.user_id': data.userId }, { password: data.password }, { new: true })
.then(() => {
return res.redirect('/change-password');
});
}
})
.catch((err) => {
return next(err);
});
});
You can return a promise chain from within a then function.
Depending on your version of Node, you may also be able to re-write this using async / await. It generally makes things easier to reason about.
router.post('/change-password', verifyToken, csrfProtection, async (req, res, next) => {
if (!req.body.password_current || !req.body.password_new) {
req.flash('info', 'Please fill in both fields.');
return res.redirect('/change-password');
}
try {
const data = {};
data.password = req.body.password_new;
const decoded = await tokenHandler.verifyToken(req.cookies.token);
const user = await User.findOne({ '_id.user_id': decoded.user });
data.userId = ObjectId(user._id.user_id);
const allowed = await bcrypt.compare(req.body.password_current, user.password);
if (!allowed) {
return res.redirect('/change-password');
} else {
await User.findOneAndUpdate({ '_id.user_id': data.userId }, { password: data.password }, { new: true });
}
return res.redirect('/change-password');
} catch (err) {
return next(err);
}
});
You need Node.js >= 7 to use async/await.
I have problem with my node.js bot to roulette. Bot is fully set up but when I launching it, it gives me error "Bot stopped with code null". Can someone help me to fix it?
Here is the error screenshot: http://i.imgur.com/zfZoMD4.png
Code:
function login(err, sessionID, cookies, steamguard) {
if(err) {
logger.error('Auth error');
logger.debug(err);
if(err.message == "SteamGuardMobile") {
account.twoFactorCode = SteamTotp.generateAuthCode(account.shared_secret);
logger.warn('Error in auth: '+account.twoFactorCode);
setTimeout(function() {
community.login(account, login);
}, 5000);
return;
}
process.exit(0);
}
logger.trace('Sucesfully auth');
account.sessionID = sessionID;
account.cookies = cookies;
community.getWebApiKey('csgobananas.com', webApiKey);
community.startConfirmationChecker(10000, account.identity_secret);
}
function webApiKey(err, key) {
if(err) {
logger.error('Cant make apikey')
logger.debug(err);
process.exit(0);
return;
}
account.key = key;
logger.trace('API key bot '+account.accountName+' '+account.key);
offersSetup();
community.loggedIn(checkLoggedIn);
}
function offersSetup() {
logger.trace('Loaded steam-tradeoffers');
offers.setup({
sessionID: account.sessionID,
webCookie: account.cookies,
APIKey: account.key
});
}
function checkLoggedIn(err, loggedIn, familyView) {
if((err) || (!loggedIn)) {
logger.error('We arent logged in')
process.exit(0);
} else {
logger.trace('Logged in');
account.auth = true;
bot_manager.js code:
var forever = require('forever-monitor');
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
database: 'placeholder',
host: 'placeholder',
user: 'placeholder',
password: 'placeholder'
});
query('SELECT * FROM `bots`', function(err, row) {
if((err) || (!row.length)) {
console.log('Failed request or empty bot table');
console.log(err);
return process.exit(0);
}
console.log('List of bots:');
row.forEach(function(itm) {
console.log('Launching bot# '+itm.id);
var bot = new (forever.Monitor)('bot.js', {
args: [itm.id]
});
bot.on('start', function(process, data) {
console.log('Bot with ID '+itm.id+' started');
});
bot.on('exit:code', function(code) {
console.log('Bot stopped with code '+code);
});
bot.on('stdout', function(data) {
console.log(data);
});
bot.start();
});
});
function query(sql, callback) {
if (typeof callback === 'undefined') {
callback = function() {};
}
pool.getConnection(function(err, connection) {
if(err) return callback(err);
console.info('Database connection ID: '+connection.threadId);
connection.query(sql, function(err, rows) {
if(err) return callback(err);
connection.release();
return callback(null, rows);
});
});
}