How to url rewrite in nodejs and receive values on server end - node.js

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);
});

Related

Cannot get Express to find routes

I am working on making adjustments to teammates code and I haven't been able to understand how they have done their routing. I am attempting to have Express run a middleware script when an end-user goes to a new session of the web application.
I don't know what to test next to figure out how they have done their routing.
Main.js
// Dependencies
var http = require('http');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var busboy = require('connect-busboy');
var cors = require('cors');
var mongoose = require('mongoose');
// Configuration
var config = require('./config');
var twilio = require('twilio');
// Database
mongoose.connect(config.database);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function(){
console.log('Connected to database');
});
var app = express();
app.set('port', process.env.PORT || 3000);
// Setup middleware
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(config.sessionSecret));
app.use(express.static(path.join(__dirname, 'dist')));
app.use(busboy());
app.use(cors({
origin: true,
credentials: true
}));
app.all('/*',function(req,res){
twilio.notifyOnSession();
console.log('Message Sent');
})
var server = http.createServer(app);
var port = app.get('port');
server.listen(port);
console.log('Listening on port ' + port);
// Load server router
require('./router')(app);
/router/index.js
var path = require('path');
module.exports = function(app){
console.log('Initializing server routing');
require('./auth')(app);
require('./api')(app);
// Determine if incoming request is a static asset
var isStaticReq = function(req){
return ['/auth', '/api', '/js', '/css'].some(function(whitelist){
return req.url.substr(0, whitelist.length) === whitelist;
});
};
// Single page app routing
app.use(function(req, res, next){
if (isStaticReq(req)){
return next();
}
res.sendFile(path.join(__dirname, '../dist/index.html'));
});
};
Your app.all('/*' is swallowing all requests before they can hit your router.
Don't do that.
I was able to resolve the issue by creating a new route with twilio.js and having the router look for the url twilio/new. Thanks all for the help.

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.

NodeJS Sessions (Or dont share values between users)

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?

Mongodb db.get('usercollection') not working corretly

Issue is that db is not working properly
app.js
var express = require('express');
var path = require('path');
var http = require('http');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/nodetest1');
var routes = require('./routes');
var users = require('./routes/users');
var app = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.use(function(req,res,next){
req.db = db;
next();
});
routes/index.js
exports.index = function(req, res){
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{},function(e,docs){
res.render('userlist', {
"userlist" : docs
});
});
};
When I run userlist I get an error on line db.get('usercollection'). When I log req.db it is undefined.
How to resolve it?
you can directly use your db module in the index.js file
module.exports = (function() {
'use strict';
var apiRoutes = express.Router();
var Server = mongo.Server;
var Db = mongo.Db;
var BSON = mongo.BSONPure;
function connexionDataBase(callback){
var server = new Server('your db URL', 27017, {auto_reconnect: true});
db = new Db('you Db', server);
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'you Db' database");
callback(err,db);
}
else{
console.log("not Connected to 'you Db' database");
callback(err,db);
}
});
})();
and in your app.js your can redirect the app routes to index.js :
var express = require('express');
var index = require('./index');
var app = express();
app.use('/index',index);

Node + Redis not quite working

I have this initialisation code;
app.use(cookieParser);
var redis = require('redis');
var redisOptions = {}
redisOptions.client = redis.createClient(<removed>, 'pub-redis-12124.us-east-1-2.3.ec2.garantiadata.com');
app.use(session({
store: new RedisStore(redisOptions),
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
In my routing, I have this;
router.post('/login', function (req, res) {
var users = req.db.get('users');
users.findOne({email: req.body.email}, function (err, user) {
console.log(user);
if (req.body.password == user.password) {
req.session.id = user._id;
console.log("id:" );
res.send('successful login' + req.session.id);
} else {
// Make sure to log failed auth requests
var log = req.db.get('failed_auth');
var fail_info = {};
fail_info.email = req.body.email;
fail_info.ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
fail_info.timestamp = Date.now();
log.insert(fail_info, function(doc) {
res.send('bad creds');
});
}
});
});
However when I try to go through this code, I get this error;
TypeError: Cannot set property 'id' of undefined
My Redis server is one of the free hosted ones from redislabs. I'm not sure if I need to authenticate although I don't think that I do. Any tips on the way forward?
edit:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')();
var session=require('express-session');
var RedisStore = require('connect-redis')(session);
// New Code
var monk = require('monk');
var db = monk('localhost:27017/manpoints');
var routes = require('./routes/index');
var account = require('./routes/account')
var app = express();
// 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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
Ignore the mess/unused stuff, I've been trying lots of different things trying to get this to work.

Resources