Jawbone API Paginated Results with 'page_token' - json

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

Related

Configuring NodeExpress to deploy and prevent Internal Error 500

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.

NodeJS to Postman Result

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

want to convert my webapp to desktop app with data persistence

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

node.js data fetch in json model error

I am new to node.js
I was just making an simple application
my data is inserting properly into the database as well as fetching also from the database
But the problem is when I am trying to access it in json model it is giving me error
var express = require('express');
/*
* body-parser is a piece of express middleware that
* reads a form's input and stores it as a javascript
* object accessible through `req.body`
*
* 'body-parser' must be installed (via `npm install --save body-parser`)
* For more info see: https://github.com/expressjs/body-parser
*/
var bodyParser = require('body-parser');
// create our app
var app = express();
// instruct the app to use the `bodyParser()` middleware for all routes
app.use(bodyParser.urlencoded({ extended: true }));
// A browser's default method is 'GET', so this
// is the route that express uses when we visit
// our site initially.
app.get('/', function(req, res){
// The form's action is '/' and its method is 'POST',
// so the `app.post('/', ...` route will receive the
// result of our form
var html = '<form action="/" method="post">' +
'Enter your name:' +
'<input type="text" name="userName" placeholder="Put your name" />' +
'<br>' +'Enter your city:'+'<input type="text" name="userCity" placeholder="Put your city" />' +
'<br>' +'Enter your state:'+'<input type="text" name="userState" placeholder="Put your state" />' +
'<br>' +'Enter your country:'+'<input type="text" name="userCountry" placeholder="Put your country" />' +
'<br>' +
'<button type="submit">Submit</button>' +
'</form>';
res.send(html);
});
// This route receives the posted form.
// As explained above, usage of 'body-parser' means
// that `req.body` will be filled in with the form elements
app.post('/', function(req, res){
var userName = req.body.userName;
var userCity = req.body.userCity;
var userState = req.body.userState;
var userCountry = req.body.userCountry;
// var document = {userName:userName,userCity:userCity,userState:userState,userCountry:userCountry};
var html = 'Hello: ' + userName + '.<br>' +'City: ' + userCity + '.<br>'+'State: ' + userState + '.<br>'+'country: ' + userCountry + '.<br>'+
'Try again.';
// res.send(html);
//res.send(JSON.stringify(doc));
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = require('mongodb').MongoClient;
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
//HURRAY!! We are connected. :)
console.log('Connection established to', url);
/* var userName = req.body.userName;
var userCity = req.body.userCity;
var userState = req.body.userState;
var userCountry = req.body.userCountry;
var document = {userName:userName, userCity:userCity,userState:userState,userCountry:userCountry};*/
// do some work here with the database.
var insertDocument = function(db, callback) {
db.collection('test').insertOne( {
"userName" :userName,
"userCity" : userCity,
"userState" : userState,
"userCountry" :userCountry ,
}, function(err, result) {
assert.equal(err, null);
console.log("Inserted a document into the test collection.");
callback(result);
});
};
var findDocument = function(db, callback) {
var cursor =db.collection('test').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.log(doc);
// res.contentType('application/json');
res.send(JSON.stringify(doc));
/* app.get('/test', function(req, res, next) {
res.json(doc);
});*/
} else {
callback();
}
// res.send(JSON.stringify(doc));
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
findDocument(db, function() {
db.close();
});
});
});
/* var document = {name:"David", title:"About MongoDB"};
db.collection('test').insertOne(document, function(err, records) {
if (err) throw err;
console.log("Record added as "+records[0]._id);
});*/
//Close connection
// db.close();
}
});
});
app.listen(3000);
Please help me to get rid off the problem.
Thank you..
The error I am getting is cann't set headers after they are send
This kind of error usually means that you try using res.send(...) multiple times from the same route.
Here you can see that in your find document, you use a cursor.each, and send your result inside this cursor.each. This means that you send multiple results from the same route.
What you should do instead is having a variable that you use to store your result before sending it once everything is retrieved.

nodejs puts post data into new json

When I sending post request by this code:
var data = '{data: 1111}'; // = JSON.stringify(message);
console.log('NotifySplitter: ' + data);
var options = cfg.splitterOptions;
options.headers['Content-Length'] = Buffer.byteLength(data)
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
... and getting data by this code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/', function(request, response){
var query = request.body;
console.log(request.body);
response.end();
});
request.body contains:
{'{data: 1111}': ''}
instead expected {data: 1111}. Is it normal? How to get normal data without replacing external {} in origin data before post?
You have to set up an appropriate content-type. If you're sending json, add options.headers['Content-Type'] = 'application/json' to your request.
Also, {data: 1111} is not a JSON, it's JSON5. While it's better all around, it's not supported by default express.bodyParser(), so watch out for that.