How to add node-schedule module to the expressjs app - node.js

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.

Related

Is it possible to see an image using postman?

I have created a Node.JS REST API server, and tried to test it by sending a GET request on https://localhost:3443/public/images/logo.png that logo.png image exist and I can see it in the directory. But the Postman gives me Not Found 404 error message.
This is my imagesRouter.js:
const express = require('express');
const bodyParser = require('body-parser');
const Images = require('../models/images');
var authenticate = require('../authenticate');
const imagesRouter = express.Router();
const cors = require('./cors');
imagesRouter.use(bodyParser.json());
imagesRouter.options('*', cors.corsWithOptions, (req, res) => { res.sendStatus(200); } );
imagesRouter.route('/')
//.options(cors.corsWithOptions, (req, res) => { res.sendStatus(200); })
.get(cors.cors, (req,res,next) => {
Images.find({})
.then((images) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(images);
}, (err) => next(err))
.catch((err) => next(err));
})
module.exports = imagesRouter;
And this is my app.js file:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var usersRouter = require('./routes/usersRouter');
var imagesRouter = require('./routes/imagesRouter');
const uploadRouter = require('./routes/uploadRouter');
const Images = require('./models/images');
//const uploadRouter = require('./routes/uploadRouter');
//const favoriteRouter = require('./routes/favoriteRouter')
var config = require('./config');
const mongoose = require('mongoose');
//mongoose.set('useCreateIndex', true);
mongoose.Promise = require('bluebird');
var passport = require('passport');
var authenticate = require('./authenticate');
// Connection URL
const url = config.mongoUrl;
const connect = mongoose.connect(url, {
//useMongoClient: true,
/* other options */
useNewUrlParser: true ,
useUnifiedTopology: true
});
connect.then((db) => {
console.log("Connected correctly to server");
}, (err) => { console.log(err); });
var app = express();
// Secure traffic only
app.all('*', (req, res, next) => {
if (req.secure) {
return next();
}
else {
res.redirect(307, 'https://' + req.hostname + ':' + app.get('secPort') + req.url);
}
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use('/', index);
app.use('/users', usersRouter);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/public/images',imagesRouter);
app.use('/imageUpload',uploadRouter);
//app.use('/imageUpload',uploadRouter);
//app.use('/favorites',favoriteRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
EDIT: This is my app files tree:
You'll need to specify the base of the static router to point to the public folder. You are currently "mounting" the public folder on the root route in the current code. You can change this line
app.use(express.static(path.join(__dirname, 'public')));
To:
app.use('/public', express.static(path.join(__dirname, 'public')));
Alternatively, you can call the endpoint from postman (or any other client) as: https://localhost:3443/images/logo.png

ExpressJS setting up SEO friendly route

I am new to NodeJS and I am experiencing a problem while setting up my routes. I am using i18next, i18next-express-middleware and i18next-node-fs-backend in order to create a multilingual test website.
I would like my URL to look like the following depending on the selected language:
/fr/index, for french,
/en/index, for english,
/jp/index, for japanese.
I am currently facing at least one problem. The default route does not send me to the correct URL. I am always directed to /.
Here is my server.js file:
'use strict';
var debug = require('debug');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var i18next = require('i18next');
var i18nextMiddleware = require('i18next-express-middleware');
var backend = require('i18next-node-fs-backend');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
i18next
.use(backend)
.use(i18nextMiddleware.LanguageDetector)
.init({
backend: {
loadPath: __dirname + '/locales/{{lng}}/{{ns}}.json',
addPath: __dirname + '/locales/{{lng}}/{{ns}}.missing.json'
},
ns: ["ns.common"],
defaultNS: "ns.common",
fallbackNS: "ns.common",
fallbackLng: 'en',
preload: ['en', 'fr', 'jp'],
saveMissing: true,
removeLngFromUrl: false,
detection: {
order: ['path', 'session', 'querystring', 'cookie', 'header']
},
});
app.use(i18nextMiddleware.handle(i18next));
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '/public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function () {
debug('Express server listening on port ' + server.address().port);
});
Here is my index.js file:
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/:lng', function (req, res) {
res.header("Content-Type", "text/html; charset=utf-8");
res.render('index', {});
});
module.exports = router;
The project is articulated as follows:
locales
|_en
ns.common.json
|_fr
ns.common.json
|_jp
ns.common.json
public
|_fonts
|_images
|_javascripts
|_stylesheets
routes
index.js
user.js
views
server.js
Everything is working fine if I enter manually the URL.
Can someone help me detect what is wrong in my code?
Thanks in advance for your answers.
Edit
As pointed out by Kishan, I use the following code, in order to redirect users to the correct locale. Thus, I am using a cookie to store the locale of a user. I ddo not know if it is a safe nor the most optimized way of doing things, but it works.
Here is the index file:
'use strict';
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function (req, res) {
res.redirect(req.cookies.locale + '/index');
});
router.get('/:lng/index', function (req, res) {
res.header("Content-Type", "text/html; charset=utf-8");
res.render('index', {});
});
/* Change locale */
router.post('/locale', function (req, res) {
res.cookie('locale', req.body.locale, { maxAge: 900000, httpOnly: true });
res.json({ status: 'success', redirect: '/' + req.body.locale + '/index'});
});
module.exports = router;
You need to add a route for / (root) in the index.js.
In the above code, the route gets into index.js but not find the path for /(root).
So add the route like...
router.get('/', function (req, res) {
// YOUR LOGIC
});
in your index.js.

i18n cannot use localization url

I am trying to add localization to my website. I install i18n, create 2 localization json files in spanish and english and I add the configuration in app.js file. The app.js file is this:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var i18n = require("i18n");
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var request = require('request');
var flash = require('express-flash');
var winston = require('winston');
winston.add(winston.transports.File, { name: 'app-info', maxFiles: 3, filename: 'logs/app-info.log', level: 'info' });
winston.add(winston.transports.File, { name: 'app-error', maxFiles: 3, filename: 'logs/app-error.log', level: 'error' });
require('dotenv').config();
var app_port = process.env.APP_PORT;
var fs = require('fs');
var app = express();
app.listen(app_port, function(){
console.log('listening on *:' + app_port);
});
// Include php notifications
var notifications = require('./phpmonitor');
// Define routes
var routes = require('./routes/index');
var login = require('./routes/login');
var doctors = require('./routes/doctors');
var new_appointment = require('./routes/new_appointment');
var new_appointment_medicine = require('./routes/new_appointment_medicine');
var new_appointment_psychology = require('./routes/new_appointment_psychology');
var appointments = require('./routes/appointments');
var videoconference = require('./routes/videoconference');
var user = require('./routes/user');
var user_doctor = require('./routes/user_doctor');
var doctor = require('./routes/doctor');
var history = require('./routes/history');
var public = require('./routes/public');
var ajax = require('./routes/ajax');
var patients = require('./routes/patients');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// i18n setup
i18n.configure({
locales:['es', 'en'],
defaultLocale: 'es',
objectNotation : true,
queryParameter: 'lang',
cookie: 'i18n',
syncFiles: true,
updateFiles: true,
directory: __dirname + '/locales'
});
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(i18n.init);
app.locals.request = request.defaults({jar: true});
app.locals.winston = winston;
// Set session
app.use(session({
store: new RedisStore,
secret: 'Y0V3NJS58jP61lfQjPn8gm99Cb2Ppl6y',
resave: true,
saveUninitialized: false,
}));
// Global use, set locale and basic locals
app.use(function(req, res, next) {
var cookie = req.cookies.i18n;
if (cookie === undefined) {
res.cookie('i18n', 'es', { maxAge: 900000000, httpOnly: true });
}
// Wizard cookie
var cookie_wizard = req.cookies.omnidoctor_wizard;
if (cookie_wizard === undefined) {
res.locals.wizard_cookies = 'pending';
}
// Accept cookies
var accept_cookies = req.cookies.omnidoctor_cookies;
if (accept_cookies === undefined) {
res.locals.accept_cookies = 'pending';
}
i18n.setLocale(req, i18n.getLocale());
app.locals.api = process.env.API_URL;
app.locals.site_url = process.env.SITE_URL;
app.locals.site_protocol = process.env.SITE_PROTOCOL;
app.locals.socket_port = process.env.SOCKET_PORT;
res.locals.analytics = process.env.ANALYTICS;
// Load moment with i18n locale
app.locals.moment = require('moment');
app.locals.moment.locale(i18n.getLocale());
next();
});
app.use('/', routes);
app.use('/', login);
app.use('/doctors', doctors);
app.use('/history', history);
app.use('/new-appointment/medicine', new_appointment_medicine);
app.use(['/new-appointment/psychiatry', '/new-appointment/psychology'], new_appointment_psychology);
app.use('/new-appointment', new_appointment);
app.use('/appointments', appointments);
app.use('/videoconference', videoconference);
app.use('/', user);
app.use('/', user_doctor);
app.use('/', public);
app.use('/doctor', doctor);
app.use('/ajax', ajax);
app.use('/patients', patients);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
/*app.listen(3500, function () {
console.log("express has started on port 3500");
});*/
module.exports = app;
I want to make it work when I write the url mywebsite.com/en or mywebsite.com/en but it doesn't find them I tried to follow this documentation:
https://www.npmjs.com/package/i18n
and look in diferent forums but none of the solutions worked for me. What is missing to make it work properly? I saw that the routes have to be modified but I try that as well and it did't work.
EDIT
I changed a bit the app.js file following another tutorial that I saw in the web. Now When I go to mywebsite.com/en it works perfectly but when I go to mywebsite.com/es it does't translate it.
So if I have this in es.json file translation:
{
login:{
title: "Bienvenido"
}
}
When I go to mywebsite.com/es there will appear login.title
In the router/index.js I have this:
router.get('/', requireLogin, function(req, res, next) {
request = req.app.locals.request;
res.setLocale(req.cookies.i18n);
if( req.session.role == 'doctor' ) {
var locals = {
i18n: res
};
res.render('index', locals);
}
});
router.get('/es', function (req, res) {
res.cookie('i18n', 'es');
res.redirect('/')
});
router.get('/en', function (req, res) {
res.cookie('i18n', 'en');
res.redirect('/')
});
You configured it well so i guess your issue is in the use on the i18n library, the problem is that you didn't shared it.
I would recommand going over this tuturial:
https://www.sitepoint.com/how-to-implement-internationalization-i18n-in-javascript
And making sure you use the lirary in the right way, for exmple if you what to write a headline use it as such:
var headline = i18n.__('Main Headline');

Unable to post on nodejs in heroku

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;

Node.js post method is failing with 500 error

I am new to node.js. I am developing node js application using VS 2015. Below is my server code (app.js)
In one of routes (trains.js) I defined a simple post method like below. Thing is it is working fine from localhost. But once I deploy to azure websites, POST method is throwing Internal server error.
Can some one help me with this? Please let me know if you need any further details.
//Here is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var socketio = require('socket.io');
var global = require('./routes/globals.js');
GLOBAL._ = require('lodash');
GLOBAL.KEY = 'xxxxxxxxxxxxxxxxxxxxxx';
var availability = require('./routes/availability');
var fare = require('./routes/fare');
var stations = require('./routes/stations');
var pnr = require('./routes/pnr');
var route = require('./routes/route');
var trains = require('./routes/trains');
var app = express();
app.socket = socketio();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.set('port', process.env.PORT || 3000);
app.use('/availability', availability);
app.use('/fare', fare);
app.use('/stations', stations);
app.use('/pnr', pnr);
app.use('/route', route);
app.use('/trains', trains);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
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
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.socket.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log('Message Received: ', msg);
socket.broadcast.emit('message', msg);
});
});
global.io = app.socket;
module.exports = app;
//Here is my train.js
var express = require('express');
var http = require('http');
var router = express.Router();
var utils = require("./utils.js");
var global = require('./globals.js');
router.get('/', function (req, res) {
var options = {
host: 'www.xxxxxxx.com',
path: '/test/xxxxxx/'
};
var parameters = {
fscode : 'xxxx',
tscode: 'xxxx',
//date: '',
//'class': '',
//orderby: '',
format: 'json',
pbapikey: '9xxxxxxxxa'
};
options.path += utils.getQueryString(parameters);
options.path += "pbapisign/" + utils.getHmacSHA1Signature(parameters);
callback = function (response) {
var data = "";
response.on('data', function (chunk) {
data += chunk;
});
response.on('end', function () {
console.log(data);
res.send(data + "<h1>" + utils.hello() + "</h1>");
});
}
http.request(options, callback).on('error', function (error) {
console.log(error);
res.status(400).send(error.Message)
}).end();
});
router.post('/check', function (req, res) {
// console.log('Request -', req);
// console.log('Response -', res);
var data = {
request : "HELLO",
response: "VAMSI"
}
global.io.sockets.emit('NEW_CONTACT', data);
res.status(200).send('NEW DATA').end();
});
module.exports = router;
It seems that your code has not any obvious bug.
So if you can share some information for more detail, such as for error or deployment, I think it's helpful for investigating the issue.
Meanwhile, please try to install NTVS for your VS2015 and follow the wiki page Advanced Debugging - Remote Debugging on Windows Azure to debug your application.

Resources