Unable to post on nodejs in heroku - node.js

I have a nodejs app running on Heroku. Here is the server.js file
var express = require('express')
, cors = require('cors')
, app = express();
var http = require('http').Server(app);
var io = require("socket.io").listen(http);
app.use(cors());
require('./modules/routes.js')(app,io);
app.set('port', process.env.PORT || 5000);
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
Here is my routes.js
"use strict";
const bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var time = require('express-timestamp');
var Promise = require('promise');
var momentjs = require('moment');
var _ = require('lodash');
var method = routes.prototype;
function routes(app, io) {
app.use(time.init);
app.use(cookieParser());
app.use(session({ secret: 'asdo8rter65edfgfd53wet34634632y4bluaq', resave: true, saveUninitialized: true }));
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(bodyParser.json());
app.post('/testHeroku', function(req, res) {
console.log(req);
res.write(JSON.stringify({
process: "success"
}));
res.end();
});
}
method.getroutes = function() {
return this;
}
module.exports = routes;
I'm trying to access /testHeroku from an ionic app running in android emulator.
Ionic code:
vm.testHeroku = function(){
console.log('testing heroku');
var testdata = {
url: config.baseURL + 'testHeroku',
dataServer: {
serverTaskRequest: 'getUADSF'
}
}
runajax.runajax_function(testdata, function (testdataResponse) {
if (testdataResponse.process == 'success') {
alert(testdataResponse.process);
}
});
};
Here goes my config.baseURL = abcd-1234.herokuapp.com (This is example for the heroku app url)
I don't receive any return form the http call.
Code for run_ajax service
.service('runajax', ['$http', function ($http) {
this.runajax_function = function (request, callback) {
var url = request.url;
var dataServer = request.dataServer;
// console.log('runajax function called -> ' + url);
// console.log(dataServer);
$http.post(url, dataServer).success(function (data, status, headers, config) {
callback(data);
})
.error(function () {
callback(status);
});
}
}])

I got it working. There was an error with app.set('port', process.env.PORT || 5000); I changed it to var port = process.env.PORT || 8080;

Related

How to add node-schedule module to the expressjs app

I am new to Nodejs and Expressjs. I am thinking of having a script running continously in the background without interrupting application. There are many scheduling NodeJs modules (such as node-scheduling, later etc.) available but I couldn't figure how to include them into my ExpressJs app.
Besides that where I should be including this module; at the application level or at the router.
I hope environment is not an issue, I am running this app on Windows 7 32 bit box.
I have used Yeoman Generator to create ExpressJs App. Copy and pasting code from the files generated by generator.
config.js
var path = require('path'),
rootPath = path.normalize(__dirname + '/..'),
env = process.env.NODE_ENV || 'development';
var config = {
development: {
root: rootPath,
app: {
name: 'nodejswebsocketapp'
},
port: process.env.PORT || 3000,
},
test: {
root: rootPath,
app: {
name: 'nodejswebsocketapp'
},
port: process.env.PORT || 3000,
},
production: {
root: rootPath,
app: {
name: 'nodejswebsocketapp'
},
port: process.env.PORT || 3000,
}
};
module.exports = config[env];
express.js
var express = require('express');
var glob = require('glob');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compress = require('compression');
var methodOverride = require('method-override');
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
next();
}
module.exports = function(app, config) {
var env = process.env.NODE_ENV || 'development';
app.locals.ENV = env;
app.locals.ENV_DEVELOPMENT = env == 'development';
app.set('views', config.root + '/app/views');
app.set('view engine', 'jade');
// app.use(favicon(config.root + '/public/img/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cookieParser());
app.use(compress());
app.use(express.static(config.root + '/public'));
app.use(methodOverride());
app.use(allowCrossDomain);
var controllers = glob.sync(config.root + '/app/controllers/*.js');
controllers.forEach(function (controller) {
require(controller)(app);
});
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
if(app.get('env') === 'development'){
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err,
title: 'error'
});
});
}
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {},
title: 'error'
});
});
};
app.js
var express = require('express');
var config = require('./config/config');
var app = express();
var expressWs = require('express-ws')(app);
require('./config/express')(app, config);
app.listen(config.port, function () {
console.log('Express server listening on port ' + config.port);
});
After this a controller file that I have created
scheduleTaskController.js
var express = require('express'),
router = express.Router(),
schedule = require('node-schedule');
module.exports = function (app) {
app.use('/', router);
app.use('/schedule', router);
};
router.get('/schedule', function (req, res, next) {
console.log(schedule.RecurrenceRule());
var rule = new schedule.RecurrenceRule();
rule.second = 30;
schedule.scheduleJob(rule, function(){
console.log(new Date(), 'The 30th second of the minute.');
});
});
Hitting the URL '/schedule' yields into nothing. not in browser and not in the command prompt where I am expecting result of console.log.
I would create a scripts folder and then require that file from your server.js file.

String Compression in Node.JS

I'm using the following code to make GET request and to store the result in the local variable using node.js, the result stored in the variable is intended to send as sms. How do I compress the data stored in the result prior to sending it as sms? Please help
var express = require('express');
var request = require("request")
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello Cruel World!');
});
var bodyParser = require('body-parser');
var WEBHOOK_SECRET = "my secret here";
app.post('/telerivet/webhook',
bodyParser.urlencoded({ extended: true }),
function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
}
request("http://boilerpipe-web.appspot.com/extract?url=http: //"+content+"&extractor=LargestContentExtractor&output=text&extractImages=", function(error, response, data) {
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content:" " + data}
]
});
res.status(200).end();
});
}
);
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
Assuming you want to compress the response to the browser, you will likely want to add a GZIP middleware package:
var compress = require('compression');
app.use(compress());

Cannot GET/ Error In Node js With Heroku

I'm working on node js backend which receives user sms from android app using telerivet webhook API.everytime when i run the app atheroku it gives me cannot GET/ error ,my code for index.js is
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var WEBHOOK_SECRET = "62DZWMCCFFHTTQ44CG3WUQ94CTT7GAAN";
app.post('/telerivet/webhook',
bodyParser.urlencoded({ extended: true }),
function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message!,Our Backend Is Still in Alpha Stage,Hang Tight" }
]
});
}
res.status(200).end();
}
);
app.listen(process.env.PORT || 5000);
please help,where im i doing wrong
it gives me cannot GET/ error when i run the app on browser,and also doesnt reply for sms when testing with the app
I found the way out,this is my new code:
var express = require('express');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
response.send('Hello World!');
});
var bodyParser = require('body-parser');
var WEBHOOK_SECRET = "62DZWMCCFFHTTQ44CG3WUQ94CTT7GAAN";
app.post('/telerivet/webhook', bodyParser.urlencoded({ extended: true }),function(req, res) {
var secret = req.body.secret;
if (secret !== WEBHOOK_SECRET) {
res.status(403).end();
return;
}
if (req.body.event == 'incoming_message') {
var content = req.body.content;
var from_number = req.body.from_number;
var phone_id = req.body.phone_id;
// do something with the message, e.g. send an autoreply
res.json({
messages: [
{ content: "Thanks for your message!,Stay Tuned for Awesome " }
]
});
}
res.status(200).end();
}
);
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});

Nodejs Socket.io is not connecting

I'm connecting Socket in my App but the configuration is mismatched because of which socket is not connecting. What could be the problem? I'm referring to "Mastering Web Application Development with Express" for structuring
app.js
var express = require('express');
var app = express();
var morgan = require('morgan'); //HTTP request logger middleware for node.js
var flash = require('connect-flash');
var multiparty = require('connect-multiparty');
var cookieParser = require('cookie-parser');
var cookieSession = require('express-session');
var bodyParser = require('body-parser'); //Node.js body parsing middleware
var methodOverride = require('method-override');
var errorHandler = require('errorhandler');
var config = require('./config.js');
var passport = require('passport');
var fs = require('fs');
var sessionStore = new cookieSession.MemoryStore();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
morgan.token('id', function getId(req) {return req.id })
var accessLogStream = fs.createWriteStream(__dirname + '/log/systemAccessWithToken.log', {flags: 'a'})
app.use(assignId)
app.use(morgan(':id :method :url :response-time', {stream: accessLogStream}))
function assignId(req, res, next) {
next()
}
app.use(bodyParser.json()); //middleware that only parses json
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride(function(req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
var method = req.body._method;
delete req.body._method;
return method;
}
}));
app.use(cookieParser());
app.use(cookieSession({
store: sessionStore,
secret: config.sessionSecret,
cookie: {maxAge: config.sessionMaxAge}
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash());
if (app.get('env') === 'development') {
app.use(errorHandler());
}
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.set('Access-Control-Allow-Methods', 'GET, POST');
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
app.use(express.static(__dirname + '/public'));
require('./app/passport')(passport); // pass passport for configuration
var socketcon = require('./app/mainSocket.js');
socketcon.socketconfig(app, io, sessionStore, cookieParser);
require('./routes/controller.js')(app, passport); // load our routes and pass
server.listen(config.port);
mainSocket.js
var modules = require('../externalModules.js');
var dbConnection = modules.dbConnection;
var cryptography = modules.cryptography;
var onlineUsers = {};
var onlineUsersSocketid = {};
exports.socketconfig = function(app, io, sessionStore, cookieParser) {
io.set('authorization', function(data, callback) {
if (!data.headers.cookie) {
return callback('No cookie transmitted.', false);
}
cookieParser(data, {}, function(parseErr) {
if (parseErr) {
return callback('Error parsing cookies.', false);
}
var sidCookie = (data.secureCookies && data.secureCookies['myuser.sid']) || (data.signedCookies && data.signedCookies['myuser.sid']) || (data.cookies && data.cookies['myuser.sid']);
sessionStore.load(sidCookie, function(err, session) {
if (err || !session || !session.passport.user) {
callback('socket Not logged in.', false);
} else {
data.session = session;
socketSession = session;
console.log("socketSession value " + JSON.stringify(socketSession));
callback(null, true);
}
});
});
});
io.sockets.on('connection', function(socket) {
console.log("socket connected");
console.log("socket.id " + socket.id);
socket.encryptedUserid = socketSession.passport.user.userId;
var devicetype = "web";
var secUserSalt = socketSession.passport.user.salt;
socket.userid = cryptography.crypto.fnDecryption(
socket.encryptedUserid, secUserSalt);
var isMobile = socketSession.passport.user.isMobile;
var devicetype = "web";
if (isMobile) {
devicetype = "mobile";
}
socket.on('user:join', function() {
//==============================develpoment(Aug21)====================
if (socket.userid in onlineUsersSocketid) {
onlineUsersSocketid[socket.userid].sockets_ids
.push(socket.id);
onlineUsersSocketid[socket.userid].devicetype
.push(devicetype);
} else {
onlineUsersSocketid[socket.userid] = {
"sockets_ids": [socket.id], // array for all sockets id of this user
"devicetype": [devicetype]
}
}
console.log("onlineUsersSocketid " + JSON.stringify(onlineUsersSocketid));
});
socket.on('disconnect', function() {
delete onlineUsersSocketid[socket.userid];
});
});
} // end of export module
What could be the issue?
Per the socket.io docs, these are two server-side initialization sequences that should work:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
or
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
You don't have either of these.

Node/Express.js request handling with different files

//server.js
app.use('/shelf', require('./books').middleware);
//books.js
var app = new express.Router();
app.post('/books' , function (req, res) {
console.log('here');
});
module.exports = app;
This is what i did so far; my server runs under server.js, and when i make a '/shelf/books' request, it first goes to server.js and then to the books.js file and logs 'here'. but i want to add a request handler(a different file, handler.js i.e) where i want to to validate if the post param is a number and than redirect it to books.js if it is.
app.js
var express = require('express')
, http = require('http')
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(require('./handler').middleware);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
handler.js
var express = require('express')
var books = require('./books')
var router = new express.Router();
router.get('/shelf/:book_id', function(req, res){
var onlyNumbers =req.param('book_id').match(/^\d+$/)
if (onlyNumbers){
var parsedNumber = parseInt(req.param('book_id'));
if( parsedNumber ) {
books(parsedNumber)
console.log("Parsed number is : " + parsedNumber)
res.end("Parsed number is : " + parsedNumber)
}
}
else {
console.log("not a number : " + req.param('book_id'))
res.end("not a number : " + req.param('book_id'))
}
res.end('');
})
module.exports = router;
books.js
var express = require('express')
var app = new express.Router();
module.exports = function(req, res) {
console.log("\t in books module")
};
How about this?
//handler.js
module.exports = function (req, res, next) {
req.check_result = /\d+/.test(req.body.yourfield);
};
// book.js
app.post('/books' , function (req, res) {
if(req.check_result) {
// your code
} else {
// your code
}
});
// server.js
app.use('/shelf', require('./handler'));
app.use('/shelf', require('./books').middleware);

Resources