NodeJS Sessions (Or dont share values between users) - node.js

I have this simples nodejs app.
var express = require('express')
var app = express();
var cont = 0
app.get('/', function (request, response) {
cont ++;
response.send('Cont ' + cont)
}).listen(3000, 'localhost');
I would like cont value start in 0 for each session (or user). This snippset share cont value between sessions.

You can use express-session module. https://www.npmjs.com/package/express-session

I follow ponury-kostek's sugestion and install 'express-session', this is my code now.
var express = require('express');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser());
app.use(expressSession({secret:'somesecrettokenhere'}));
app.use(bodyParser());
var cont = 0;
app.get('/', function(req, res){
var html = '';
if (req.session) {
req.session.cont++
html += 'cont session is: ' + req.session.cont;
}
res.send(html);
});
app.listen(3000);
But how set initial value for cont and iterated it?

Related

TypeError: Cannot read property 'listOrderJson' of undefined

Im trying to link a route to a controller vs doing the code within the route definiton. Here is my controller:
const {mongoose} = require('../db/mongoose');
const {Order} = require('../models/order');
module.exports.listAllJson = function(req, res) {
res.send({"Here": "something"});
}
And here is my server.js file:
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var schedule = require('node-schedule');
var {mongoose} = require('./db/mongoose');
var {Order} = require('./models/order');
var {orderController} = require('./controllers/orderController');
var app = express();
app.use(bodyParser.json());
app.get('/orders', (req, res) => {
orderController.listAllJson().bind(orderController);
});
app.listen(3000, () => {
console.log('Started on port 3000');
});
module.exports = {app};
When I hit my /orders route using postman I get:
TypeError: Cannot read property 'listOrderJson' of undefined error.
I added the 'bind' part to the function call after searching here on stack overflow a ton, but it didn't help. What am I doing wrong here?
orderController is { listAllJson: fn } so you can simply destructure and use it.
var express = require('express');
var bodyParser = require('body-parser');
var fs = require('fs');
var schedule = require('node-schedule');
var {mongoose} = require('./db/mongoose');
var {Order} = require('./models/order');
var {listAllJson} = require('./controllers/orderController');
var app = express();
app.use(bodyParser.json());
app.get('/orders', listAllJson);
app.listen(3000, () => {
console.log('Started on port 3000');
});
module.exports = {app};
Also minor note use res.json({"Here": "something"}); it does the stringifying and set the headers.

Node express cannot get static file

This is the picture of my server
https://drive.google.com/file/d/1GA57RyYsc5ik1pSlLhAGtgGjbp_vLFoH/view?usp=sharing
When I go to http://localhost:3000/
I get the error message: Cannot Get/
myserver.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Whenever you are trying to visit any url on the browser , then browser makes a GET request to that url, in your case you are not sending any response on the url: "http://localhost:3000/. You can try something like this.
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve("./client") + '/index.html'));
});
Check the naming you used, it shows myserver.js instead of server.js as in the picture you uploaded.
Check your routing on line 10 of you code
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
. try this edited codes
server.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./server/lions');
var tigerRouter = require('./server/tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Express static directory is given client but it is present on parent directory.
So i have resolve this issue with path module and now this will work for you.
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var path = require('path')
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static(path.join(__dirname, '../client')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Your code works fine after commenting the following three lines of your code:
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use('/lions', lionRouter);
Check if any error is present in LionsJS.

How to url rewrite in nodejs and receive values on server end

i want to rewrite the url like this
http://localhost:3000/page?N1=568ff78634da
and receive value on the server end
app.get('/page', function(req, res){
var x=req.body.N1;
//do something with the value
});
my server is something like this:
var express = require('express');
var mongo = require('mongodb').MongoClient;
var app = express();
var path = require('path');
var bodyParser = require("body-parser");
var url = 'mongodb://localhost:27017/test';
var assert = require('assert');
var MongoClient = require('mongodb').MongoClient;
var session = require("express-session");
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var ObjectID = require('mongodb').ObjectID;
users = [];
connections = [];
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'views')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({resave: false, saveUninitialized: true, secret:'xxxxxxxxxxxxx'}));
app.use(bodyParser.json());
using this way i am not able to receive values...
this is get request in get request the data is in query so write this
var someData=request.query.data;
in ur case
var someData=request.query.N1;
You can access the parameters using the query object, contained within the request e.g.
app.get('/page', function(req, res) {
var x = req.query.N1;
console.log('x = ' + x);
});

NodeJS Require, where do I use this?

Node JS require for the bittrex api... exactly where do it.
npm everything is installed including require...
var bittrex = require('bittrex-api');
on any page gives require is not defined
1) I'm using ui-router, server.js is not needed... I added one anyway.
var express = require('express');
var path = require('path');
//var logger = require('morgan');
//var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
//var bcrypt = require('bcryptjs');
var app = express();
app.set('port', process.env.PORT || 8080);
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/')));
app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
now I want to add the bittrex ticker on the dashboard... so on the dashboard view I add
var market = 'BTC-LTC';
var bittrex = require('bittrex-api');
I turn on the server.js file and I get the require undefined message, I turn it off same message.
What am I doing wrong?

Socket.IO and express routes

I would like to use socket.io and express routes and I have the following code:
app.js
var
http = require('http'),
path = require('path'),
passport = require('passport'),
userpassport = require('./lib/strategies/local'),
githubpassport = require('./lib/strategies/github'),
flash = require('connect-flash'),
express = require('express'),
logger = require('morgan'),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
errorhandler = require('errorhandler'),
csrf = require('csurf'),
favicon = require('serve-favicon'),
sockets = require('./lib/socket'),
app = express();
var routes = require('./routes')();
app.get('/', routes.index);
var server = http.createServer(app).listen(app.get('port'), function () {
var io = require('socket.io')(server);
io.on('connection', function (iosocket) {
sockets.setSocket(iosocket);
});
});
lib/socket.js
var socket;
exports.setSocket = function(iosocket) {
console.log('setting socket');
socket = iosocket;
}
exports.getSocket = function() {
console.log('getting socket');
return socket;
}
routes/index.js
var sockets = require('../lib/socket');
module.exports = function () {
var routes = {};
routes.index = function (req, res) {
var socket = sockets.getSocket();
socket.on('app/create', function (data) {
console.log('got app create');
});
}
This does not work, I think it's because the setSocket function that appears on app.js runs after the page was loaded, therefore when I getSocket on the route it's not the latest socket (I can console log the given socket on the route, I can see there's a socket there, but I can also see that the setSocket runs afterwards).
How can I solve this?

Resources