Error while running nodejs app on AWS Ubuntu using pm2 - node.js

While starting nodejs with express application on AWS ubuntu using pm2, logs shows below error.
Below is my app.js file
// Packages
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 app = express();
// 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.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//app.locals.basedir = path.join(__dirname, 'views');
global.__base = __dirname + '/';
var dbhelper = require('./routes/dbhelper.js');
var common = require('./routes/common.js');
var ErrorHandler = require('./routes/errorhandler.js');
var authenticationRepository = require(__base + 'repository/authentication.js');
// set up mustbe config
var mustBe = require("mustbe");
var mustBeConfig = require("./mustBeConfig");
mustBe.configure(mustBeConfig);
// Routes
var routes = require('./routes/index');
// Make database connection available to router
app.use(function (req, res, next) {
common.ActionOutput.Message = '';
common.ActionOutput.Results = [];
req.ActionOutput = common.ActionOutput;
req.ActionStatus = common.ActionStatus;
req.ApplicationCookies = common.ApplicationCookies;
req.Security = common.Security;
req.Constants = common.Constants;
console.log(req.url);
// Temp Keys
var key = common.Encrption('firstword|secondword');
var dkey = common.Decryption('3TYkoj9CgZZU+IdD+PAqC3U9xlyJuG40g2fXAJn3GB8=');
var key = req.get('Key');
var msg = null;
if (key == undefined || key == null || key == '')
msg = 'header key not found.';
else {
try {
var keys = common.Decryption(key).split('|');
if (keys.length < 2 || keys.length > 3)
msg = 'header key is incorrect.';
else
next();
} catch (err) {
msg = 'Unable to decrypt header value.';
}
}
if (msg != null) {
common.ActionOutput.Message = msg;
common.ActionOutput.Status = common.ActionStatus.Error;
return res.send(JSON.stringify(common.ActionOutput));
}
});
app.use('/', routes);
app.use(function (err, req, res, next) {
if (!err)
return next();
ErrorHandler.SaveErrorLog(req, res, null, err.message, err.stack, req.connection.remoteAddress, err.path);
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log('Exception: Not Found ' + req.url);
var APIKey = req.get('Key');
var UserKey = req.get('UserKey');
var DeviceToken = req.get('DeviceToken');
ErrorHandler.SaveErrorLog(req, res, UserKey, 'Resource not found!!!', '', req.connection.remoteAddress, req.url);
});
// 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('shared/error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
var APIKey = req.get('Key');
var UserKey = req.get('UserKey');
var DeviceToken = req.get('DeviceToken');
ErrorHandler.SaveErrorLog(req, res, UserKey, 'Resource not found!!!', '', req.connection.remoteAddress, req.url);
});
process.on('uncaughtException', function (err, abc) {
console.log('uncaughtException: ' + err);
ErrorHandler.SaveErrorLog(null, null, null, 'UnCaught exception: ' + err.message, err.stack, 'IP', err.address);
});
module.exports = app;
app.listen(3000, function () {
console.log('Server starts on port: ' + 3000);
});
netstat says below which seems to be a problem to access it from outside. Application is running after changing port but not accessible.
Please suggest.

Related

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

How to share Session across multiple route JS files in ExpressJS

First of all, I am using:
express-session#1.14.2
express#4.14.0
I am basically trying to get a login system working and when user logs in, I set session.isloggedin = true.
So this 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 session = require('express-session');
var index = require('./routes/index');
var portfolioRoute = require('./routes/portfolio');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// 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(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true,
maxAge: new Date(Date.now() + 2 * 60 * 1000) }
}));
app.use('/', index);
app.use('/portfolio', portfolioRoute);
// 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;
The index.html contains the login form.
Next, my index.js
var express = require('express');
var router = express.Router();
var util = require('util');
var api = require('../server/api.js');
var port = require('../server/portfolio.js');
var sess;
/* GET home page. */
router.get('/', function (req, res) {
sess = req.session;
console.log("SESSION IS: " + sess.isLoggedIn);
if(sess.isLoggedIn) {
res.render('portfolio', { isLoggedIn: true })
} else {
res.render('index', { isLoggedIn: false })
}
})
//END ------------
if(global.GLB_PORTFOLIO === null) {
port.getPortfolio(null, function(err, result) {
global.GLB_PORTFOLIO = result;
});
}
// API Routes
//router.use('/api', router);
router.route('/api/login')
.post(api.postLogin)
router.route('/api/portfolio')
.post(api.postPortfolio)
.get(api.getPortfolio)
//END ------------
module.exports = router;
Next, my api.js:
var util = require('util');
const backend = require('./portfolio.js');
exports.postPortfolio = function(req,res) {
backend.insertPortFolio(req.body, function(err, result) {
res.json({ result: result, error:err });
});
}
exports.getPortfolio = function(req,res) {
backend.getPortfolio(req, function(err, result) {
global.GLB_PORTFOLIO = result;
res.json({ portfolio: result, error: err });
});
}
exports.postLogin = function(req,res) {
backend.findUserByEmail(req.body.email, function(err, result) {
console.log("API: SESSION IS: " + req.session.isLoggedIn);
if(err || result === null) {
req.session.isLoggedIn = false;
} else {
req.session.isLoggedIn = true;
}
req.session.save();
res.json({ user: result, error: err });
});
}
The session variable is always undefined even after the save(). What am I doing wrong?

How do I use node on a live remote server (504 time out)

I am trying to deploy my node.js app to my web server. I have everything installed on the server side, and the app works locally. I just seem unable to connect when I try to upload it to the server. It tries to load and eventually gives me a 504 time out error.
Here's my code:
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 session = require('express-session');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var multer = require('multer');
var app = express();
var fs = require('fs');
var mongoose = require('mongoose');
var unqID;
var http = require('http');
//http
http.createServer(function(req, res){
console.log('SmartMove Running');
mongoose.connect('mongodb://localhost/smartproperty');
var db = mongoose.connection;
var routes = require('./routes/index');
var articles = require('./routes/articles');
var categories = require('./routes/categories');
var manage = require('./routes/manage');
var manager = require('./routes/manager');
var adverts = require('./routes/adverts');
var upload = require('./routes/server');
var app = express();
// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}))
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(require('connect-flash')());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/articles', articles);
app.use('/categories', categories);
app.use('/manage', manage);
app.use('/manager', manager);
app.use('/adverts', adverts);
//res.end('Done');
}).listen(8080, '127.0.0.1');
//end http
//upload
app.use(bodyParser.json());
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
//filename: function (req, file, callback) {
//callback(null, file.fieldname + '-' + Date.now());
//}
filename: function (req, file, callback) {
var advert = new Advert();
var qryId = advert._id;
callback(null, unqID + '-' + Date.now());
}
});
var upload = multer({ storage : storage }).array('userPhoto',2);
//app.get('/',function(req,res){
// res.sendFile(__dirname + "/index.html");
//});
app.post('/api/photo',function(req,res){
upload(req,res,function(err) {
console.log(req.body);
console.log(req.files);
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
//end upload
// 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: {}
});
});
module.exports = app;
I have tried to see if it will load with just a res.end. This is successful, however, with that line removed nothing loads at all.
If anyone could help that would be great.
EDIT
Ok so i have managed to get it to depoy on my server but now this is presenting a different problem. all of the files have uploaded and i can see them, when the server is running though it fails to go to any routes, and it also seems like my CSS hasnt pulled through like in my development environment. Does anyone have any ideas why this may be, it still seems to be an issue on the server side which is why i edited, however if I am wrong to do this please let me know and i will create a new question.

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.

node/express - exporting controller functionality

I am building a Node API on express which takes GET requests and uses the parameters supplied by the client to return the results of GET requests made to other API's.
In order to keep the controller thin when adding more API's I would like to export the logic within the controller into a separate .js file, and module.export those functions back in, to be used in the controller. The problem here is that the functions that are being exported do not appear to be visible within the controller.
Pasted below is before and after code to illustrate progress made so far.
app.js (before) - see router.get('/')
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 request = require('request');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var router = express.Router();
if ( app.get('env') === 'development') {
var dotenv = require('dotenv');
dotenv.load();
};
var prodAdv = require('./lib/prod-adv.js')
// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/api', router);
// 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: {}
});
});
router.get('/', function(req, res) {
request('https://openapi.etsy.com/v2/listings/active?includes=Images&keywords=' + req.param('SearchIndex') + '&limit=100&api_key=' + process.env.ETSY_KEY, function(error, response, body) {
res.header({'Access-Control-Allow-Origin': '*'});
var data = JSON.parse(body);
res.json(data);
});
});
router.use('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, accept, authorization");
next();
});
var server = app.listen(9876, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
});
module.exports = app;
This approach works, returning JSON objects. However the following approach to try and export the code does not work.
apiCaller.js
var express = require('express');
var app = express();
if ( app.get('env') === 'development' ) { var dotenv = require('dotenv'); dotenv.load(); };
var request = require('request');
var call, response;
var call = function(searchIndex) {
return request('https://openapi.etsy.com/v2/listings/active?includes=Images&keywords=' + searchIndex + '&limit=100&api_key=' + process.env.ETSY_KEY, function(error, response, body) {
response = JSON.parse(body);
});
};
module.exports.response = response;
module.exports.call = call;
app.js (after)
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 squid = require('./lib/apiCaller.js');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var router = express.Router();
if ( app.get('env') === 'development') {
var dotenv = require('dotenv');
dotenv.load();
};
var prodAdv = require('./lib/prod-adv.js')
// 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(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.use('/api', router);
// 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: {}
});
});
router.get('/', function(req, res) {
squid.call(req.param('SearchIndex'));
res.header({'Access-Control-Allow-Origin': '*'});
res.json(squid.response);
});
router.use('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, accept, authorization");
next();
});
var server = app.listen(9876, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
});
module.exports = app;
What occurs now in the browser is a 200 OK with an empty response body. console.logging the responses return undefined objects.
You need to rewrite your call function to have a callback since request(...) is asyncronous
var call = function(searchIndex, callback) {
request('https://openapi.etsy.com/v2/listings/active?includes=Images&keywords=' + searchIndex + '&limit=100&api_key=' + process.env.ETSY_KEY, function(error, response, body) {
if (!error && response.statusCode == 200) {
return callback(null, JSON.parse(body));
}
callback('error');
});
};
Only export call function, there's no need to export or even use response and no need for this line
var call, response;
Now you also need to use it a bit different way
router.get('/', function(req, res) {
res.header({'Access-Control-Allow-Origin': '*'});
squid.call(req.param('SearchIndex'), function(err, data){
if(!err) return res.json(data);
res.json({error: err});
});
});

Resources