Right now I'm using node on a virtual host, just running npm start and using it's IP to acess the node server.It's a very simple API that just acess an mysql database and returns a json. At first it works alright, however I've noticed that after few hours, running the npm start on pm2, It no longer returns the json for me. It's doesn't crash either, just don't give me back what I requested. Giving me internal error 500.
I would like to know what should I consider in order to properly use Nodejs On produciton mode. And Maybe spot what is causing me the error, since it's a very small application.
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require("cors");
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var leisRouter = require('./routes/leis');
var counterRouter = require('./routes/count')
var documentoRouter = require('./routes/documento')
var app = express();
const mysql = require('mysql2');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/leis",leisRouter)
app.use("/count",counterRouter)
app.use("/documento",documentoRouter)
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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');
});
I'm just using route : leis and documento
The leis route :
function mapDocumentType(literalType){
switch(literalType){
case 'lei':
return 1
case 'parecer':
return 11;
case 'decreto':
return 2;
case 'circular':
return 3;
case 'portaria':
return 4;
case 'emenda':
return 5;
case 'instrucaoNormativa':
return 6;
case 'comunicado':
return 7;
case 'ordemInterna':
return 8;
case 'orientacaoNormativa':
return 10;
case 'parecerNormativo':
return 12;
case 'portariaConjunta':
return 14;
case 'projetoDeLei':
return 15;
case 'publicacao':
return 16
case 'razoesDeVetoAoProjetoDeLei':
return 17;
case 'resolucaoConjunta':
return 18
case 'leiComplementar':
return 19
}
}
function getQueryFilters(query){
const q = []
Object.entries(query).some(([k,v])=>{
if(v==1){
q.push(mapDocumentType(k))
}
})
if(q.length==0)return ""
return q.toString();
}
router.get("/search/:search_content/:page",function(req,res,next){
var pageM = (req.params.page -1)*10;
let searchValue = req.params.search_content;
//No caso de numero, formata para o padrão ponto entre cada 3 casas decimais. Exemplo 1000 fica como 1.000
let numeric_repr = searchValue.toString().replace(/\B(?=(\d{3})+(?!\d))/g, '.');
if(searchValue == "tudo"){searchValue ="";}
const q = getQueryFilters(req.query);
let datesuffix = "";
console.log(numeric_repr);
if(req.query.dateend !=="" && req.query.datebegin !==""){
datesuffix = `and data_edicao BETWEEN '${req.query.datebegin}' and '${req.query.dateend}'`
}
if(q==""){
connection.query(`SELECT * FROM documento WHERE (descricao_detalhada LIKE '%`+numeric_repr+`%' OR descricao_detalhada LIKE '%`+searchValue+`%' OR
descricao_reduzida LIKE '%`+numeric_repr+`%' OR descricao_reduzida LIKE '%`+searchValue+`%' OR
num_doc ='%`+numeric_repr+`%')`+ datesuffix ,(err,rows,fields)=>{
res.json({content : rows.slice(pageM,pageM+10),row_count:rows.length})
})
}
else{
connection.query(`SELECT * FROM documento WHERE (descricao_detalhada LIKE '%`+numeric_repr+`%' OR descricao_detalhada LIKE '%`+searchValue+`%' OR
descricao_reduzida LIKE '%`+numeric_repr+`%' OR descricao_reduzida LIKE '%`+searchValue+`%' OR
num_doc ='%`+numeric_repr+`%' ) and id_tipo_documento IN (`+q+')'+datesuffix ,(err,rows,fields)=>{
res.json({content : rows.slice(pageM,pageM+10),row_count:rows.length})
})
}
})
module.exports = router;
the final mysql query works alright. However ,after certain time, the when I request this route, it just gives me internal error 500.
Related
I will try to describe my question well and what I trying to archieve
I have lots of table like this in my nodejs app
everying member I will give it a href to "/profile/"theirUsername""
after watching ton of tutorial,
I add a button href to my username
$('#pendingDepositTable').append(`
<tr>
<td>
<div class="d-flex align-items-center">
<div class="table-user-name ml-3">
<p class="mb-0 font-weight-medium">`+ response[i].id + `</p>
</div>
</div>
</td>
<td>
<a href="/profile/`+ response[i].customer + `">
`+ response[i].customer + `
</a>
</td>
<td>`+ response[i].bank + `</td>
<td>`+ response[i].amount + `</td>
<td>
<div class="badge badge-inverse-warning"> `+ response[i].status + ` </div>
</td>
<td>`+ response[i].date + `</td>
<td>
<i class="mdi mdi mdi-check-all"></i>
<i class="mdi mdi-close"></i>
</td>
</tr>
`)
}
I add this in my profile.js
router.get('/:id', function (req, res, next) {
console.log(req.params.id);
db.query("SELECT * FROM `customers` WHERE `username` = '" + req.params.id + "'", function (err, result, field) {
try {
res.render('templateMember', { customers_profile: result });
} catch (error) {
console.log(error)
}
})
Before I render the page, I use res.send(result) and get the data that I want successfully.
But all of my header and js script all messed up (I put these in partials.)
and the url all gone wrong
example my transaction page is http://localhost:3000/deposit
but if i redirect from here it become http://localhost:3000/profile/deposit
What can I do or if i miss something?
my projects folder
my app.js
var createError = require('http-errors');
var express = require('express');
var app = express();
var path = require('path');
var session = require('express-session');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
var flash = require('express-flash');
app.use(flash());
app.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true
}));
var indexRouter = require('./routes/index');
var loginRouter = require('./routes/user_signin');
var memberRouter = require('./routes/members');
var depositRouter = require('./routes/deposit');
var withdrawalRouter = require('./routes/withdrawal');
var creditTransferRouter = require('./routes/creditTransfer');
var cashBonusRouter = require('./routes/cashBonus');
var productListingRouter = require('./routes/products_listing');
var productBalanceRouter = require('./routes/products_balance');
var bankListingRouter = require('./routes/banks_listing');
var bankBalanceRouter = require('./routes/banks_balance');
var bonusRouter = require('./routes/bonus');
var profileRouter = require('./routes/profile')
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Login API
app.use('/auth', require('./routes/controllerRoute/auth'));
// Post Product API
app.use('/product_add_action', require('./routes/controllerRoute/product_add_action'));
// Add Member API
app.use('/addMemberRouter', require('./routes/controllerRoute/addMemberRouter'));
app.use('/', indexRouter);
app.use('/userSignin', loginRouter);
app.use('/member', memberRouter);
app.use('/deposit', depositRouter);
app.use('/withdrawal', withdrawalRouter);
app.use('/credittransfer', creditTransferRouter);
app.use('/cashbonus', cashBonusRouter);
app.use('/products_listing', productListingRouter);
app.use('/products_balance', productBalanceRouter);
app.use('/banks_listing', bankListingRouter);
app.use('/banks_balance', bankBalanceRouter);
app.use('/profile', profileRouter);
app.use('/bonus', bonusRouter);
app.all('/', function(req, res){
console.log(req.session)
})
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// 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;
Sorry I just found out the answer.
instead of using src="xxx.css"
it should be src="/xxx.css" The leading slash indicates that the request is relative to root not the path that is making the request.
Sorry for post the question without reviewing my code carefully.
So i have a website that runs on express with some MySQL queries to load photo albums.
The problem is that when i go to /photo everything works fine but if I refresh the page then i get a 404 NOT FOUND. Same if i go first to /photo then on another url and back to /photo.
The problem happens regardless if it's in prod or dev but only happens on my server, never on local.
here's what i get :
NotFoundError: Not Found
at /home/vincdgfq/sachalebas/app.js:53:7
at Layer.handle [as handle_request] (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:317:13)
at /home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:284:7
at Function.process_params (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:335:12)
at next (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:275:10)
at /home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:635:15
at next (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:260:14)
at Function.handle (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:174:3)
at router (/home/vincdgfq/nodevenv/sachalebas/9/lib/node_modules/express/lib/router/index.js:47:12)
If i remove all my error handlers i just get a
CANNOT GET /501.shtml
website can be found here : https://sachalebas.com/photo
Thanks in advance if anyone has got any idea where i should look for with this error i'm totally lost.
EDIT:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var session = require('express-session');
require('./controllers/userController');
const oneYear = 60 * 1000 * 60 * 24 * 7;
const xssFilter = require('x-xss-protection');
const noSniff = require('dont-sniff-mimetype');
require('dotenv').config({ path:"process.env"});
const compression = require('compression');
var indexRouter = require('./routes/index');
var app = express();
app.use(xssFilter());
app.use(noSniff());
app.use(compression());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public', {maxAge: oneYear, dotfiles:'allow'}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
maxAge: 200000
}));
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// 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;
Here's my app.js
Your issue not with backend.
I've done curl requests multiple times and I'm getting same output:
which means issue on clientside with race conditions.
to avoid it try to wrap all code: https://sachalebas.com/ressources/js/script.js
Inside of:
window.onload = function() {
// here goes all js code from ressources/js/script.js
}
or make sure You don't have blocking layer in css that being rendered before image.
Good Day how can i compute a public function to route and check it on Postman? here is my codes
router.post('/post_regular_hours/:employee_id/',function(request,response,next){
var id = request.params.employee_id;
var time_in = request.params.time_in;
var time_out = request.params.time_out;
// const timein = request.params.time_in;
// const timeout = request.params.time_out;
knexDb.select('*')
.from('employee_attendance')
.where('employee_id',id)
.then(function(result){
res.send(compute_normal_hours(response,result,diff))
})
});
function compute_normal_hours(res,result,diff){
let time_in = moment(time_in);
let time_out = moment(time_out);
let diff = time_out.diff(time_in, 'hours');
return diff;
}
I want the Diff to get posted on Postman as a result
Here is the App.js of my codes. How can i call the data from mysql query to the function and return the computed data on router post
or can you guys give the right terminologies for it.
var express = require('express');
var mysql= require('mysql');
var employee = require('./routes/employee');
var time_record = require('./routes/time_record');
var admin_employee = require('./routes/admin_employee');
var tar = require('./routes/tar');
var Joi = require('joi');
var app = express();
app.get('/hello',function(req,res){
var name = "World";
var schema = {
name: Joi.string().alphanum().min(3).max(30).required()
};
var result = Joi.validate({ name : req.query.name }, schema);
if(result.error === null)
{
if(req.query.name && req.query.name != '')
{
name = req.query.name;
}
res.json({
"message" : "Hello "+name + "!"
});
}
else
{
res.json({
"message" : "Error"
});
}
});
//Database connection
app.use(function(req, res, next){
global.connection = mysql.createConnection({
host : 'locahost',
user : 'dbm_project',
password : 'dbm1234',
database : 'dbm_db'
});
connection.connect();
next();
});
app.use('/', employee);
app.use('/employee', time_record);
app.use('/admin', admin_employee);
app.use('/tar', tar);
// 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');
});
app.listen(8000,function(){
console.log("App started on port 8000!");
});
module.exports = app;
Here is the App.js of my codes. How can i call the data from mysql query to the function and return the computed data on router po
There are a few problems with your code.
Please see explanations in the respective code chunks.
router.post('/post_regular_hours/:employee_id/',function(request,response,next){
// If you're receiving a post request
// you'll probably want to check the body for these parameters.
let id = request.params.employee_id; // make sure the param names are matching with what you post.
// This one is special because you are passing it through the url directly
let time_in = request.body.time_in;
let time_out = request.body.time_out;
knexDb.select('*')
.from('employee_attendance')
.where('employee_id',id)
.then(function(result){
// you are not sending time_in and time_out here - but difference. but difference is not calculated.
// changed the function signature a bit - you weren't using the result at all? leaving this callback here because I'm sure you want to map the used time to some user?
return response.send(compute_normal_hours(time_in, time_out))
});
});
// this function was (and still might be) incorrect.
// You were passing res and result which neither of them you were using.
// You also had time_in and time_out which were going to be undefined in the function scope. Now that we are passing them in it should be ok. Updated it so you don't have the params you don't need.
function compute_normal_hours(time_in, time_out){
// What was diff - if it's the time difference name things correctly
// You had a diff parameter passed in (which you didn't compute), a diff function called below and another variable declaration called diff.
// you were not passing time_in or time_out parameters.
// you have moment here - are you using a library?
let time_in = moment(time_in);
let time_out = moment(time_out);
let diff = time_out.diff(time_in, 'hours');
return `Computed result is: ${diff}`;
}
Important Edit
Please search for all occurences of res.render (response.render) and replace them with something like res.send - res.render is looking for the template engine
I have created a payroll webapp and have used mysql and node js to build it.
The problem is that I am not sure how to convert it to a desktop webapp.
I have used the node-mysql module for this, so do I need to change something now
or just convert it using node webkit?
How does this work, really?
Here's what my server.js looks like now. so , do I need to make any changes to the code again?
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var mysql = require('mysql');
//var ejsLint=require('./server.js');
//ejsLint.lint('attendance-data.ejs', '-p');
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'employees',
multipleStatements:true
});
app.set('view engine','ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req,res){
res.render('index');
});
var daValue=227.30;
app.get('/da',function(req,res){
res.render('da');
});
app.post('/da-data',function(req,res){
daValue = Number(req.body.da);
var data = {da :daValue};
console.log('da is :',daValue);
res.render('da-data.ejs',data);
});
app.get('/add-employee',function(req,res){
res.render('add-employee');
});
app.post('/add-employee',function(req,res){
res.status(200).send();
console.log('employee '+req.body.name + ' added');
});
connection.connect(function(err){
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
app.post('/form',function (req,res){
//employee details from add-employee.html page
var name=req.body.name;
var designation = req.body.designation;
var pan = req.body.pan;
var aadhar = req.body.aadhar;
var bank = req.body.bank;
var basicSalary = req.body.salary;
var allowance = req.body.allowance;
var grossSalary = req.body.salarygross;
var esi = req.body.esi;
var uan = req.body.uan;
var details = {name:name,designation:designation,pan:pan,aadhar:aadhar,
bank:bank,basic_salary:basicSalary,other_allowances:allowance,gross_salary:grossSalary,esi:esi,uan:uan};
// for sending data as objects into database
// use {name of database column : name of the variable where it's value is stored}
// example {wages_rate is the name of database column : wagesRate is the variable where
// value is stored}
var query = connection.query('INSERT INTO employee_details SET ?',details,function(err,result){
if(err){
console.log(err);
}
console.log(query.sql);
});
res.status(200).send('employee ' + name + 'with salary of '+salary+ ' added');
});
app.get('/show',function (req,res){
connection.query('SELECT * FROM employee_details',function(err,rows){
if(err) throw err;
console.log('Data received');
console.log(rows);
var data ="Id "+"<strong>" +" name "+" designation "+" uan"+"</strong>";
for(var i=0;i<rows.length;i++){
data = data+"<br>" + (i+1)+". "+rows[i].name +" "+rows[i].designation+" "+rows[i].uan+"<br>";
}
res.send(data);
});
});
var rowsLength;
var salaryFromRow;
var salaryArr=[];
var allowanceFromRow;
var allowanceArr=[];
var designationArr=[];
app.get('/attendance',function (req,res){
connection.query('SELECT * FROM employee_details',function(err,rows){
if(err) {
throw err;
}else{
rowsLength = rows.length;
for(var i=0;i<rowsLength;i++){
salaryFromRow = rows[i].salary;
salaryArr.push(salaryFromRow);
allowanceFromRow = rows[i].allowance;
allowanceArr.push(allowanceFromRow);
designationArr.push(rows[i].designation);
console.log('designation is ',designationArr);
}
res.render('attendance',{rows:rows});
}
});
});
app.post('/attendance-data',function(req,res){
var uanFromHtml;
var nameFromHtml;
var daysPresent;
var attendance;
var nameForm;
var designation;
var monthFromHTML;
var t;
var realBasicSalary;
var realOtherAllowances;
var realGrossSalary;
var pfBasic;
var esiGross;
var pTax=0;
var netAmount;
var advance=0;
var finalData = [];
for(var i=1;i<=rowsLength;i++){
var dataArr = [];
var finalTable = [];
attendance = "attendance"+i;
t=i-1;
salaryForPerson = salaryArr[i];
allowanceForPerson = allowanceArr[i];
console.log('req.body is ', req.body);
daysPresent = Number(req.body[attendance]);
nameFromHtml = req.body.name[t];
var nameArr = req.body.name;
uanFromHtml = req.body.uan[t];
monthFromHTML = req.body.monthyear;
var uanArr = req.body.uan;
realBasicSalary = Math.ceil((req.body.basicsalary[t])*(daysPresent/30)) ;
realOtherAllowances = Math.ceil((req.body.otherallowance[t])*(daysPresent/30));
realGrossSalary = Math.ceil((req.body.grosssalary[t])*(daysPresent/30));
console.log('realBasicSalary is '+realBasicSalary+' and realGrossSalary is '+realGrossSalary+' and realOtherAllowances is '+ realOtherAllowances);
pfBasic = Math.ceil((12/100)*realBasicSalary);
esiGross = Math.ceil((1.75/100)*realGrossSalary);
if(realBasicSalary>10000 && realBasicSalary<=15000){
pTax = 110;
}else if(realBasicSalary>=15001 && realBasicSalary<=25000){
pTax = 130;
}else if(realBasicSalary>=25001 && realBasicSalary<=40000){
pTax = 150;
}else if(realBasicSalary>=40001){
pTax = 200;
}
netAmount = realGrossSalary - (pTax + pfBasic + esiGross + advance);
console.log('realGrossSalary is '+realGrossSalary + ' and realBasicSalary is '+realBasicSalary+
'pTax is '+ pTax+ 'pfBasic is '+pfBasic +'esiGross is '+esiGross);
console.log('namefromhtml is : ', nameFromHtml);
console.log('attendance is :',attendance);
console.log('days present is :',daysPresent);
console.log('monthyear is : ',monthFromHTML);
dataArr.push(monthFromHTML,uanFromHtml,nameFromHtml,daysPresent,realBasicSalary,realOtherAllowances,realGrossSalary,pTax);
finalData.push(dataArr);
/* uanArr.push(uanFromHtml);
nameArr.push(nameFromHtml);
daysArray.push(daysPresent);
*/
console.log('dataArr is : ',dataArr);
console.log('finalData is : ',finalData);
}
var attendanceData = {monthyear :monthFromHTML,rows:rowsLength,uanarr:uanArr,designationarr:designationArr,
namearr:nameArr,finaldata:finalData,realbasicsalary:realBasicSalary,realgrosssalary:realGrossSalary,ptax:pTax,advance:advance};
connection.query("INSERT INTO attendance_details(month_year,uan,name,days_present,real_basic_salary,other_allowances,gross_salary,ptax) VALUES ?",
[finalData], function(err) {
if (err){
var errors = err;
console.log(errors);
res.send(errors);
}else{
//put database query for inserting values here
res.render('attendance-data.ejs', attendanceData);
}
});
});
/*
app.get('/final',function(req,res){
connection.query('SELECT name,designation,salary,wages_rate FROM employee_details;SELECT uan,da,days_present,total_wages FROM attendance_details;',function(err,rows){
if(err){
console.error('MySQL — Error connecting: ' + err.stack);
}else{
var rowsNumber = rows.length;
console.log('rows is :',rows);
var nameFinal;
var designationFinal;
var salaryFinal;
var wagesrateFinal;
var uanFinal;
var daFinal;
var daysFinal;
var totalwagesFinal;
var nameFinalarr = [];
var designationFinalarr =[];
var salaryFinalarr = [];
var wagesrateFinalarr =[];
var uanFinalarr =[];
var daFinalarr =[];
var daysFinalarr = [];
var totalwagesFinalarr =[];
for(var i=0;i<rowsNumber;i++){
nameFinalarr.push(rows[i].name);
designationFinalarr.push(rows[i].designation);
salaryFinalarr.push(rows[i].salary);
wagesrateFinalarr.push(rows[i].wages_rate);
uanFinalarr.push(rows[i].uan);
daysFinalarr.push(rows[i].da);
daysFinalarr.push(rows[i].days_present);
totalwagesFinalarr.push(rows[i].total_wages);
}
console.log('nameFinalarr is :', nameFinalarr);
console.log('daysFinalarr is :', daysFinalarr);
}
res.render('final',{rows:rowsNumber,name:nameFinal,designation:designationFinal,salary:salaryFinal,wagesrate:wagesrateFinal,uan:uanFinal,da:daFinal,
days:daysFinal,
totalwages:totalwagesFinal});
});
});
*/
app.get('/select-month',function(req,res){
connection.query('SELECT month_year,name FROM attendance_details',function(err,rows){
if(err){
throw err;
}else{
var rowsLength = rows.length;
console.log('rows is ',rows);
res.render('select-month.ejs',{rows:rows});
}
});
});
app.get('/salary-sheet',function(req,res){
var month = req.query.selectpicker;
var employeeName = req.query.selectpicker2;
console.log('employeeName is ',employeeName);
connection.query('SELECT * FROM attendance_details WHERE month_year='+"'"+month+"' AND name='"+employeeName+"'",function(err,rows){
if(err){
throw err;
}else{
var rowsLength = rows.length;
console.log('rows is ',rows);
var uanarr=[];
var namearr=[];
var daysarr=[];
var realBasicSalaryarr=[];
var realOtherAllowancesarr=[];
var grossSalaryarr=[];
var ptaxarr=[];
var advance=0;
for(var i=0;i<rowsLength;i++){
uanarr.push(rows[i].uan);
namearr.push(rows[i].name);
daysarr.push(rows[i].days_present);
realBasicSalaryarr.push(rows[i].real_basic_salary);
realOtherAllowancesarr.push(rows[i].other_allowances);
grossSalaryarr.push(rows[i].gross_salary);
ptaxarr.push(rows[i].ptax);
}
console.log('realBasicSalaryarr is ',realBasicSalaryarr);
console.log('namearr is ',namearr);
res.render('salary-sheet.ejs',{advance:advance,rows:rows,monthyear:month,uanarr:uanarr,namearr:namearr,daysarr:daysarr,basicsalaryarr:realBasicSalaryarr,
realotherallowancesarr:realOtherAllowancesarr,realgrosssalaryarr:grossSalaryarr,ptaxarr:ptaxarr});
}
});
});
app.get('/add-company',function(req,res){
res.render('add-company.ejs');
});
app.get('/style.css',function(req,res){
res.sendFile(path.join(__dirname,'/style.css'));
});
app.get('/main.js',function(req,res){
res.sendFile(path.join(__dirname,'/main.js'));
});
app.get('/cmain.js',function(req,res){
res.sendFile(path.join(__dirname,'/cmain.js'));
});
var port=8080;
app.listen(8080,function(req,res){
console.log(`Payroll app listening on port ${port}!` );
});
Could you tell me how to convert this to a desktop app?
In order to make this work offline, in other words, stand-alone, you'll need to revisit your approach regarding persistence. MySQL is not something I'd attempt to bundle with the application. You would ideally use something from the link Yonghoon Lee suggested, as you need the app to have an embedded database instead of an external one.
I've had success doing something similar, although switching to IndexDB meant I had to rewrite all my queries as it's a NoSQL database. Please resist using Web SQL database, it's not standard and could disappear at any time.
Other than that, I don't see anything that's an obvious problem to convert to a NWJS application. You can refer to the official documentation for some examples of how to get started.
It cannot easily be ported. You should not expect the people on stackoverflow to do all the work for you. It is not a simple task but i will try to guide you trough it.
1.) understand what NWJS is. NWJS ist not just a node.js server but also a client. That means you can use both the code of node.js and javascript code that is ment to run on the client.
2.) You server js is not necessary. The entry point of you application is no server js file but an index.html file.
3.) You js code should be added into the tag of the index html. Her you can create a main.js file with the code you want to run and add it as a script tag.
4.) Install mysql into your nwjs package with npm install mysql --save
You have to run this command in the folder that has you package.json
5.) If you want to use routes you have to install express.js
The routes will be localhost routes on your computer
Now you have to consider what you really want to do? From where should the routes be accessible? Would you want an app where you have buttons that you can click and then provide data to the mysql database?
If you really have the interest to port it to nwjs you have to understand how nwjs works. I have given you the first steps but without further information I cannot give you more advises.
Wish you the best of luck. If you understand the structure of nwjs it will be easy to port it ;)
The Jawbone API returns paginated results of 10 json objects per result set. How does one obtain the rest of the paginated results?
The API documentation for the sleeps method indicates the existence of a page_token argument in the next object of the result set. My output below is missing this. Furthermore,the FAQ indicates this page_token takes an INT (presumably epoch) timestamp.
2nd: "page_token" parameter: if the request contains the "page_token" parameter, the API will return all the workouts, in
reverse order, (capped by "limit" or default of 10) that were
completed before that page_token. The page_token is a timestamp, and
there's a special case, when the request comes with page_token=0 which
is interpreted as passing page_token = CURRENT_TIMESTAMP, ie, give all
the workouts (with a limit)
I am able to authenticate with the API and return a set of 10 results (first paginated page)... but no page_token.
...snip json...
"links": {
"next": "/nudge/api/v.1.0/users/jMdCUPXZ-InYXo1kcdOkvA/sleeps?start_time=1424699101&updated_after=0&limit=10&end_time=1438723789"
},
"size": 10
Have I misunderstood the documentation? Could it be the documentation is out of date (wrong)? Or more likely, I'm completely misunderstanding this and writing horrible JS for my node.js ...
Can someone set me straight and show me how I can retrieve ALL results, not just the first page?
var express = require('express');
var app = express();
var port = process.env.PORT || 5000;
var passport = require('passport');
var config = require('./config.json');
var ejs = require('ejs');
var https = require('https');
var fs = require('fs');
var bodyParser = require('body-parser');
var jbStrategy = require('passport-oauth').OAuth2Strategy;
var jsonfile = require('jsonfile');
var util = require('util');
var path = require('path');
/* Calculate date range */
var $today = new Date()
var $start = new Date($today); $start.setDate($today.getDate() - 180);
var $end = new Date($today);
var $startDate = Math.floor(($start).getTime()/1000);
var $endDate = Math.floor(($end).getTime()/1000);
app.use(express.logger('dev')); // log every request to the console
app.use(bodyParser.json()); // read cookies (needed for auth)
app.use(express.static(__dirname + '/public'));
app.set('view engine', 'ejs');
app.set('views', __dirname + '/views');
app.use(passport.initialize());
/* Default Authentication Path */
app.get('/',
passport.authorize('jawbone', {
scope : config.jawboneAuth.scope,
failureRedirect: '/'
})
);
/* oauth callback from jawbone */
app.get('/done', passport.authorize('jawbone', {
scope : config.jawboneAuth.scope,
failureRedirect: '/'
}), function(req, res) {
var result = JSON.parse(body); console.log(result);
res.redirect('/sleeps');
}
);
app.get('/sleeps', function(req, res) {
var options = {
access_token : config.jawboneAuth.accessToken,
refresh_token : config.jawboneAuth.refreshToken,
client_id : config.jawboneAuth.clientID,
client_secret : config.jawboneAuth.clientSecret
};
if (!config.jawboneAuth.accessToken) {
// if there's no accessToken, go get one
res.redirect('/');
} else {
var up = require('jawbone-up')(options);
var page_token = [];
do {
up.sleeps.get({
page_token : page_token,
start_time : $startDate,
end_time : $endDate
}, function(err, body) {
if (err) {
console.log('Error receiving Jawbone UP data');
res.send(err);
} else {
try {
var result = JSON.parse(body);
var next_page_path = result.data.links.next;
//var next_page_token = next_page_path.split(path.sep);
//var page_token = next_page_token[5];
//page_token = result.data.links.next
console.log(result.data);
res.json(result);
} // end try
catch(err) {
console.log(err);
res.render('userdata', {
requestTime: 0,
jawboneData: 'Unknown result'
});
} // end catch(err)
} // end else
} //end callback fun
); // end up.sleeps.get()
} // end do
while(page_token[0] > 1);
} // end if
}); // end sleeps route
// Setup the passport jawbone authorization strategy
passport.use('jawbone', new jbStrategy({
clientID : config.jawboneAuth.clientID,
clientSecret : config.jawboneAuth.clientSecret,
authorizationURL: config.jawboneAuth.authorizationURL,
tokenURL : config.jawboneAuth.tokenURL,
callbackURL : config.jawboneAuth.callbackURL,
scope : config.jawboneAuth.scope,
passReqToCallback : true
}, function(req, accessToken, refreshToken, profile, done) {
// establish a pseudo user session.
var user = {};
// If there's no preexisting accessToken,
// write one to the config file.
if (!config.jawboneAuth.accessToken){
config.jawboneAuth.accessToken = accessToken;
config.jawboneAuth.refreshToken = refreshToken;
jsonfile.writeFile('./config.json', config, {spaces: 2}, function(err) {
console.error(err);
})
}
done(null, user);
}));
// HTTPS
var sslOptions = {
key : fs.readFileSync('./.server.key'),
cert : fs.readFileSync('./.server.crt')
};
var secureServer = https.createServer(sslOptions, app).listen(port, function(){
console.log('Listening on ' + port);
});
Turns out there is an undocumented limit parameter that has replaced the page_token.
The Jawbone Developer documentation is currently out of date. As is their FAQ (API section Question# 12).
A GET request like this seems to do the trick
https://jawbone.com/nudge/api/v.1.1/users/#me/sleeps?start_time=1388603458&end_time=1420139458&limit=1000