TypeError: Cannot read property 'weight' of undefined - undefined

im new and still learning, my project is to make a BMI calculator using node.js, js, HTML.. when i run my code it works no problem on the webpage except when i try to calculate i end up with this error.
i have looked online but i couldnt understand or solve my problem. thank you in advanced for any help.
MINGW32 ~/Desktop/Calculator
$ nodemon calculator.js
[nodemon] 2.0.4
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node calculator.js`
calc server started!!!
TypeError: Cannot read property 'weight' of undefined
at C:\Users\pc\Desktop\Calculator\calculator.js:30:38
at Layer.handle [as handle_request] (C:\Users\pc\Desktop\Calculator\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\pc\Desktop\Calculator\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\pc\Desktop\Calculator\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\pc\Desktop\Calculator\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\pc\Desktop\Calculator\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\pc\Desktop\Calculator\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\pc\Desktop\Calculator\node_modules\express\lib\router\index.js:275:10)
at expressInit (C:\Users\pc\Desktop\Calculator\node_modules\express\lib\middleware\init.js:40:5)
at Layer.handle [as handle_request] (C:\Users\pc\Desktop\Calculator\node_modules\express\lib\router\layer.js:95:5)
in my file for calculator.js
/*eslint-env es6*/ // Enables es6 error checking for that file
/*eslint-env jquery*/ // Enables error checking for jquery functions
/*eslint-env browser*/ // Lets you use document and other standard browser functions
/*eslint no-console: 0*/ // Lets you use console (for example to log something)
//jshint esversion:6
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.get(bodyParser.urlencoded({extended: true}));
//app.get("/",function(req, res){
// res.sendFile(__dirname+"/index.html");
//});
//app.post("/",function(req,res){
// var n1 = Number(req.body.n1);
// var n2 = Number(req.body.n2);
// var result = n1 + n2;
//
// res.send("The result of the calculation is "+ result);
//});
app.get("/bmicalculator",function(req, res){
res.sendFile(__dirname+"/bmiCalculator.html");
});
app.post("/bmicalculator", function(req, res){
var weight = parseFloat(req.body.weight);
var height = parseFloat(req.body.height);
var bmi = weight / (height * height);
res.send("Your BMI is " + bmi);
});
app.listen(1990, function(){
console.log("calc server started!!!");
});

Related

404 on page refresh of MySQL query with NodeJS

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.

Gulp doesn't create link to a folder

Can not create a symbolic link to the /var/www/project/bower_components/bootstrap/less/mixins folder via Gulp JS. I tried to specify the desired path via the nodeJS.
VARIANT 1
CODE:
var gulp = require('gulp');
var path = require('path');
var debug = require('gulp-debug');
var symlink = require('gulp-sym');
gulp.task('symlink-deploy', function () {
var mixins = gulp
.src('' + path.resolve() + 'bower_components/bootstrap/less/mixins/')
.pipe(symlink('' + path.resolve() + 'assets/less/'))
.pipe(debug({title: 'unicorn:'}));
return Promise.all([mixins]);
});
gulp.task('default', ['symlink-deploy']);
RESULT:
user#user-ThinkPad-Edge-E545:/var/www/project$ gulp symlink-deploy
[17:18:44] Using gulpfile /var/www/project/gulpfile.js
[17:18:44] Starting 'symlink-deploy'...
[17:18:44] Finished 'symlink-deploy' after 28 ms
events.js:141
throw er; // Unhandled 'error' event
^
Error: EISDIR: illegal operation on a directory, read
at Error (native)
user#user-ThinkPad-Edge-E545:/var/www/project$
I have also was tried set path manually:
VARIANT 2
CODE:
var gulp = require('gulp');
var path = require('path');
var debug = require('gulp-debug');
var symlink = require('gulp-sym');
gulp.task('symlink-deploy', function () {
var mixins = gulp
.src('/home/user/www/project/bower_components/bootstrap/less/mixins')
.pipe(symlink('/home/user/www/project/assets/less'))
.pipe(debug({title: 'unicorn:'}));
return Promise.all([mixins]);
});
gulp.task('default', ['symlink-deploy']);
RESULT:
user#user-ThinkPad-Edge-E545:/var/www/project$ gulp symlink-deploy
[17:57:55] Using gulpfile /var/www/project/gulpfile.js
[17:57:55] Starting 'symlink-deploy'...
[17:57:55] Finished 'symlink-deploy' after 27 ms
events.js:141
throw er; // Unhandled 'error' event
^
Error: Destination file exists (/home/user/www/project/assets/less) - use force option to replace
at Transform._transform (/var/www/project/node_modules/gulp-sym/index.js:55:26)
at Transform._read (/var/www/project/node_modules/gulp-sym/node_modules/readable-stream/lib/_stream_transform.js:184:10)
at Transform._write (/var/www/project/node_modules/gulp-sym/node_modules/readable-stream/lib/_stream_transform.js:172:12)
at doWrite (/var/www/project/node_modules/gulp-sym/node_modules/readable-stream/lib/_stream_writable.js:237:10)
at writeOrBuffer (/var/www/project/node_modules/gulp-sym/node_modules/readable-stream/lib/_stream_writable.js:227:5)
at Transform.Writable.write (/var/www/project/node_modules/gulp-sym/node_modules/readable-stream/lib/_stream_writable.js:194:11)
at write (/var/www/project/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:623:24)
at flow (/var/www/project/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:632:7)
at DestroyableTransform.pipeOnReadable (/var/www/project/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:664:5)
at emitNone (events.js:67:13)
user#user-ThinkPad-Edge-E545:/var/www/project$
Can't understand why it is't working.

JSON.parse gives error on gulp task

I have this gulp task
gulp.task('replace', function () {
// Get the environment from the command line
var env = args.env || 'localdev';
// Read the settings from the right file
var filename = env + '.json';
console.log(filename)
var settings = JSON.parse(fs.readFileSync('./config/' + filename, 'utf8'));
// Replace each placeholder with the correct value for the variable.
gulp.src('./js/constants.js')
.pipe(replace({
patterns: [
{
match: 'apiUrl',
replacement: settings.apiUrl
}
]
}))
.pipe(gulp.dest('./js'));
});
I always get this error when i execute my code
SyntaxError: Unexpected token /
at Object.parse (native)
at Gulp.<anonymous> (/home/k1ngsley/Projects/loanstreet-rea-app/gulpfile.js:86:23)
at module.exports (/home/k1ngsley/Projects/loanstreet-rea-app/node_modules/gulp/node_modules/orchestrator/lib/runTask.js:34:7)
at Gulp.Orchestrator._runTask (/home/k1ngsley/Projects/loanstreet-rea-app/node_modules/gulp/node_modules/orchestrator/index.js:273:3)
at Gulp.Orchestrator._runStep (/home/k1ngsley/Projects/loanstreet-rea-app/node_modules/gulp/node_modules/orchestrator/index.js:214:10)
at Gulp.Orchestrator.start (/home/k1ngsley/Projects/loanstreet-rea-app/node_modules/gulp/node_modules/orchestrator/index.js:134:8)
at /usr/lib/node_modules/gulp/bin/gulp.js:129:20
at process._tickCallback (node.js:448:13)
at Function.Module.runMain (module.js:499:11)
at startup (node.js:119:16)
at node.js:935:3
But if i remove the JSON.parse and just run
var settings = fs.readFileSync('./config/' + filename, 'utf8');
I get no error but the code is not parsed as json. What do i do? Why does JSON.parse not work in gulpfile.js
Any help appreciated
Solved this error by doing this
var setting = fs.readFileSync('./config/' + filename, 'utf8');
var settings = JSON.parse(JSON.stringify(setting));

Unable to run gulp task

I'm trying to run a simple gulp-sass task, but I'm getting this error:
[22:42:14] Starting 'sass'...
[22:42:14] Finished 'sass' after 10 ms
events.js:72
throw er; // Unhandled 'error' event
^
Error: File not found with singular glob
at Glob.<anonymous> (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\index.js:34:30)
at Glob.EventEmitter.emit (events.js:95:17)
at Glob._finish (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:171:8)
at done (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:158:12)
at Glob._processSimple2 (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:640:12)
at D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:628:10
at Glob._stat2 (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:724:12)
at lstatcb_ (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\glob.js:716:12)
at RES (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\node_modules\inflight\inflight.js:23:14)
at f (D:\Development\WebStorm\calliope\node_modules\gulp\node_modules\vinyl-fs\node_modules\glob-stream\node_modules\glob\node_modules\once\once.js:17:25)
I Installed gulp both globally and locally as dev depency.
Here's my task:
var gulp = require("gulp"),
sass = require("gulp-sass");
gulp.task("sass", function(){
gulp.src('assets/sass/*.scss')
.pipe(sass())
.pipe(gulp.dest('assets/css'))
});
The error is not so clear, by the way the Exception is throwed by a wrong link ( resource not found )
Yes, that is correct. The error is thrown whenever the resource is not found. I wrote a function to prevent such an occurrence in my files.
run "npm install fs --save".
then add this to your gulpfile
var fs = require('fs');
var validateResources = function (resources) {
resources.forEach(function (resource) {
if (!fs.existsSync(resource)) {
throw resource + " not found!";
}
});
};
With this, you will be safe to some extent.

app crash in appfog using node js mysql

I have an app hosted in appfog using node-express and mysql( and backbone js in the client side), it works fine in localhost but when deploy the app works fine for a moment and after a time crash( if i restart in the console of appfog admin the same thing happens)
this is part of code for connection mysql
var mysql = require("mysql")
var env = JSON.parse(process.env.VCAP_SERVICES);
var creds = env['mysql-5.1'][0]['credentials'];
console.log(creds)
var client = mysql.createConnection({
host: creds.host || "localhost",
user: creds.user,
password: creds.password,
port: creds.port,
database: "savelinks"
});
The code in app.js
var express = require("express");
var path = require("path");
var port = 9000;
var request = require('request');
var cheerio = require('cheerio');
var app = module.exports = express();
console.log(process.env.VCAP_SERVICES)
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
var server = require("http").createServer(app)
app.get("/", function(req,res){
res.render("index");
});
/*
* GET ALL LINKS ON LOAD PAGE
*/
app.get("/links", function(req, res){
links = db.client.query("SELECT * FROM links ORDER BY created DESC", function(err, result){
if(!err){
res.json(result)
}
});
});
// more routers
app.listen(process.env.VCAP_APP_PORT || port, function(){
console.log("server run in port " + port)
});
This is the log that app fog shows
events.js:71
throw arguments[1]; // Unhandled 'error' event
^
Error: Connection lost: The server closed the connection.
at Protocol.end (/mnt/var/vcap.local/dea/apps/savelinks-0-ca19c96d36d4701debe7fe46752707c5/app/node_modules/mysql/lib/protocol/Protocol.js:73:13)
at Socket.onend (stream.js:66:10)
at Socket.EventEmitter.emit (events.js:126:20)
at TCP.onread (net.js:417:51)
Any idea for solve this problem?
I had the same kind of issue in production, but not on my personal development machine. My node server uses node-mysql with connect on an Ubuntu VM. My node server would crash and restart now and then throughout the day with the same kind of error you are seeing.
The following approach explained on the node-mysql GitHub page worked to solve the problem for me:
https://github.com/felixge/node-mysql#server-disconnects