Port Errors running node.js application - javascript

i cloned an node.js application and , to set up, i did an npm install and npm install -g nodemon , i wanted to run it locally on port 3000, so in my app.js file i added
app.listen(3000, () => console.log('Server running on port 3000!'))
and then i tried to run it by using node app.js but i am getting this errors
this is my app.js file
var express = require('express');
var engine = require('ejs-locals');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var fileUpload = require('express-fileupload');
var request = require('request');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var routes = require('./routes/index');
var testgrid = require('./routes/testgrid');
var hsdes_query = require('./routes/hsdes_query');
var find_coverage = require('./routes/find_coverage');
var url = "mongodb://127.0.0.1:27017/onegrid_int";
var config = require('./config');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('ejs', engine);
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(fileUpload());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var manual_ti_payload_template = {
"attributes": [],
"blackList": "string",
"description": "string",
"endDate": "2019-02-03T21:28:12.567Z",
"id": "string",
"itemId": "string",
"key": "string",
"name": "ascii string",
"namespace": "ascii string",
"ownerIdsid": "string",
"planningAttributes": [],
"resources": [],
"resourcesVersions": [],
"startDate": "2019-02-03T21:28:12.567Z",
"type": "manualitem",
"version": 0,
"whiteList": "string"
}
app.post('/updategtaproc', function(req, res){
console.log("updategtaproc", req.body)
var username = "Lab_FMVPOSumit";
var password = "bdzxl12$";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
request.post( {
url : 'http://gta.intel.com/procedures/api/v1/procedures/' + req.body.name,
headers : {
"Authorization" : auth
},
json: {"description": req.body.description, "steps":req.body.steps}
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
res.send(body)
});
});
app.post('/createnupdategtaproc', function(req, res){
console.log("createnupdategtaproc", req.body)
var username = "Lab_FMVPOSumit";
var password = "bdzxl12$";
var auth = "Basic " + new Buffer(username + ":" + password).toString("base64");
var ti_payload = Object.assign({}, manual_ti_payload_template);
ti_payload.name = req.body.expected;
ti_payload.description = req.body.description;
ti_payload.ownerIdsid = username;
ti_payload.namespace = "vtt-gve-gqe"
console.log(ti_payload)
request.post( {
url : 'https://gta.intel.com/api/tp/v1/testitems',
headers : {
"Authorization" : auth
},
json: ti_payload,
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
if (body && body.itemId) {
console.log("Test case created successfully", body.itemId);
var itemId = body.itemId;
request.post( {
url : 'http://gta.intel.com/procedures/api/v1/procedures/' + body.itemId,
headers : {
"Authorization" : auth
},
json: {"description": req.body.description, "steps":req.body.steps}
}, function(error, response, body) {
console.log("updategtaproc response",error, body);
console.log("Test Procedure Uploaded Successfully");
body['itemId'] = itemId
res.send(body)
});
} else {
console.log("Failed to Create Test Case");
res.send({"message":"Failed To Create Test Case"})
}
});
});
app.post('/getgriditems/:id', function(req, res){
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid_int//getgriditems/:id unable to connect to mongodb')
}
else
{
var collection_name = (req.params.id).toLowerCase() + "-" + "griditems"
var collection = db.collection(collection_name);
var objectIdArr = [];
for (var key in req.body) {
if (req.body.hasOwnProperty(key)) {
item = req.body[key];
try {
objectIdArr.push(ObjectId(String(item)));
}
catch (err)
{
// Invalid Object ID
}
}
}
collection.find({"_id" : {"$in" : objectIdArr }}).toArray(function(err, griditems) {
if(err)
{
console.log('onegrid//getgriditems/:id unable to get grid items')
}
else
{
var paths = []
for ( var r in griditems){
//console.log('path :', result[r]['path'])
paths.push(griditems[r]['path'].join(",") + ',' + griditems[r]['testItem']['itemId'])
}
console.log("paths", paths)
var global_result_collection = db.collection("onegrid-global-results");
global_result_collection.find({"full_path" : {"$in" : paths }}).toArray(function(err, results) {
if(err)
{
console.log('onegrid//getgriditems/:id unable to get test results')
}
else
{
var metadata = {}
metadata['griditems'] = griditems
metadata['results'] = results
console.log("test_results", results)
res.send(metadata);
db.close();
}
});
}
});
}
});
});
app.post('/get_all_tags', function(req, res){
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
var collection = db.collection('user_tags');
collection.find().toArray(function(err, tags) {
if(err)
{
console.log('onegrid/manual_tests/error getting documents from collection')
}
else
{
var tag_type_ar = tags.map(a => a.type_tag);
//console.log('onegrid/manual_tests/number_of_docs/', tests.length)
//console.log('onegrid/manual_tests/tags/', tags_name)
res.send(tag_type_ar);
db.close();
}
});
}
});
});
app.post('/getsettags', function(req, res){
//console.log('body: ' + JSON.stringify(req.body));
var url = "mongodb://127.0.0.1:27017/onegrid";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/getsettags/unable to connect to mongodb')
}
else
{
var objectId = ObjectId(req.body.id);
var collection = db.collection('gve_manual_testitems');
if(req.body.op == 'set_add') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to get test item id', objectId)
}
else
{
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
if(result['tags'] && result['tags'].indexOf(req.body.newtag) != -1) {
res.send(result);
db.close();
}
else {
if(result['tags'])
{
result['tags'].push(req.body.newtag)
}
else
{
result['tags'] = [req.body.newtag];
}
collection.updateOne({ _id : objectId }, { $set: { "tags" : result['tags'] } }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to set tags')
}
else
{
console.log('tags added successfully to test item');
var test_tags = result;
if(!req.body.skip_tag_source_update) {
var user_tags = db.collection('user_tags');
var type_tag = req.body.newtag;
var type = req.body.newtag.split(":")[0]
var tag = req.body.newtag.split(":")[1]
var tag_obj = {'type':type, 'tag': tag, 'type_tag' : type_tag}
user_tags.insertOne(tag_obj, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set unable to add to user tag')
}
else
{
console.log('tags added to user_tags')
res.send(test_tags);
db.close();
}
});
}
else
{
res.send(test_tags);
db.close();
}
//var newtag = req.body.newtag;
//var tag_type = newtag.split(":")[0];
//var tag_name = newtag.split(":")[1];
//console.log(tag_type,tag_name)
}
});
}
}
});
}
if(req.body.op == 'set_remove') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to get test item id', objectId)
}
else
{
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
result['tags'].splice(result['tags'].indexOf(req.body.newtag),1);
//console.log('onegrid/getsettags/set/test item id current tag value', result['tags'])
collection.updateOne({ _id : objectId }, { $set: { "tags" : result['tags'] } }, function(err, result) {
if(err)
{
console.log('onegrid/getsettags/set/unable to set tags')
}
else
{
console.log('tags removed successfully')
//collection = db.collection('user_tags');
//var newtag = req.body.newtag;
//var tag_type = newtag.split(":")[0];
//var tag_name = newtag.split(":")[1];
//console.log(tag_type,tag_name)
res.send(result);
db.close();
}
});
}
});
}
if(req.body.op == 'get') {
collection.findOne({ _id : objectId }, function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
//console.log('tags retrieved successfully ', result['tags'])
if(result['tags'])
res.send(result['tags'].join(","));
else
res.send("");
db.close();
}
});
}
}
});
});
app.post('/gettestprocs/:id', function(req, res){
console.log('gettestprocs body: ' + (req.body.itemId));
//var url = "mongodb://127.0.0.1:27017/og1";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
var collection_name = (req.params.id).toLowerCase() + "-" + "testprocs"
var collection = db.collection(collection_name);
collection.findOne({ "id" : req.body.itemId },function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
console.log('test proc:', result)
res.send(result);
db.close();
}
});
}
});
});
app.post('/gettestprocsbyitemid', function(req, res){
//console.log('gettestprocs body: ' + (req.body));
var url = "mongodb://127.0.0.1:27017/onegrid_int";
MongoClient.connect(url, function(err, db) {
if(err){
console.log('onegrid/manual_tests/unable to connect to mongodb')
}
else
{
console.log(req.body)
/*if(String(req.body.grid_type) == "MANUAL"){
collection_name = "n_gve_manual_testprocs"
} else if(String(req.body.grid_type) == "OLD_MANUAL") {
collection_name = "gve_manual_testprocs"
} else if(String(req.body.grid_type) == "SURFACE") {
collection_name = "gve_surface_testprocs"
}
else if(String(req.body.grid_type) == "AUTO") {
}*/
//var tp = testplans.filter(function(x){return x.itemId == req.params.id})[0];
var collection_name = (req.body.testplan_id).toLowerCase() + "-" + "testprocs"
var collection = db.collection(collection_name);
collection.findOne({"id" : String(req.body.proc_id) },function(err, result) {
if(err)
{
console.log('onegrid/manual_tests/unable to get tags')
}
else
{
console.log('test proc:', result)
res.send(result);
db.close();
}
});
}
});
});
app.use('/', routes);
app.use('/testgrid', testgrid);
app.use('/hsdes_query', hsdes_query);
app.use('/find_coverage', find_coverage);
// 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(3000, () => console.log('Server running on port 3000!'))
module.exports = app;
another app.js in C:\projects\New Project\onegrid\web\node_modules\ejs-locals\example
var express = require('express')
, engine = require('../')
, app = express();
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')
// render 'index' into 'boilerplate':
app.get('/',function(req,res,next){
res.render('index', { what: 'best', who: 'me', muppets: [ 'Kermit', 'Fozzie', 'Gonzo' ] });
});
app.get('/foo.js', function(req,res,next){
res.sendfile('foo.js');
})
app.get('/foo.css', function(req,res,next){
res.sendfile('foo.css');
})
app.listen(3000);
what am i doing wrong , i just want to run it on localhost 3000. ?

Your terminal shows you running node server.js but your file is called app.js.

Related

mochajs & chaijs - Uncaught TypeError: Cannot read property 'id' of undefined

I am creating an bill tracking application that is having users create bills based on criteria I have created using javascript.
I am tasked with performing acceptance testing.
This is my code so far:
My index.js file
const express = require('express')
const app = express()
const port = 3000
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bill');
var MongoClient = require('mongodb').MongoClient
var ObjectID = require('mongodb').ObjectID
app.use(express.json())
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'))
app.set('view engine', 'pug')
app.set('views', __dirname + '/views');
var billSchema = new mongoose.Schema(
{
type: { type: String, required: true },
dueDate: { type: Date, required: true },
company: { type: String, required: true },
amtDue: { type: Number, required: true },
paidStatus: { type: String, required: true }
});
var bill = mongoose.model('bill', billSchema);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function()
{
app.get('/', (req, res) =>
{
bill.find({}, function(err, bills)
{
if (err)
{
console.log(err)
res.render('error', {})
}
else
{
res.render('index', { bills: bills })
}
});
});
app.get('/bills/new', (req, res) =>
{
res.render('bill-form', { title: "New bill", bill: {} })
});
app.get('/bills/:id/update', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.findById(id, function(err, bill)
{
if (err)
{
console.log(err)
res.render('error', {})
}
else
{
if (bill === null) {
res.render('error', { message: "Not found" })
} else {
res.render('bill-form', { title: "Update bill", bill: bill })
}
}
});
});
app.post('/bills/new', function(req, res, next) {
let newbill = new bill(req.body);
newbill.save(function(err, savedbill)
{
if (err)
{
console.log(err)
res.render('bill-form', { bill: newbill, error: err })
}
else
{
res.redirect('/bills/' + savedbill.id);
}
});
});
app.get('/bills/:id', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.findById(id, function(err, bill)
{
if (err)
{
console.log(err)
res.render('error', {})
}
else
{
if (bill === null)
{
res.render('error', { message: "Not found" })
}
else
{
res.render('bill-detail', { bill: bill})
}
}
});
});
app.post('/bills/:id/update', (req, res, next) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.updateOne({"_id": id}, { $set: req.body }, function(err, details)
{
if(err)
{
console.log(err)
res.render('error', {})
}
else
{
res.redirect('/bills/' + id)
}
});
});
app.post('/bills/:id/delete', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.deleteOne({_id: id}, function(err, product)
{
res.redirect("/")
});
});
app.post('/api/bills', (req, res) =>
{
let newbill = new bill(req.body)
newbill.save(function (err, savedbill)
{
if (err)
{
console.log(err)
res.status(500).send("There was an internal error")
}
else
{
res.send(savedbill)
}
});
});
app.post('/api/bills', (req, res) =>
{
bill.find({}, function(err, bills)
{
if(err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
res.send(bills)
}
});
});
app.get('/api/bills', (req, res) =>
{
bill.find({}, function(err, bills)
{
if(err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
res.send(bills)
}
});
});
app.get('/api/bills/:id', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.findById(id, function(err, bill)
{
if (err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
if (bill === null)
{
res.status(404).send("Not found")
}
else
{
res.send(bill)
}
}
});
});
app.put('/api/bills/:id', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
bill.updateOne({"_id": id}, { $set: req.body }, function(err, details)
{
if (err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
res.status(204).send()
}
});
});
app.delete('/api/bills/:id', (req, res) =>
{
let id = ObjectID.createFromHexString(req.params.id)
Review.deleteOne({"_id": id}, function(err)
{
if (err)
{
console.log(err)
res.status(500).send("Internal server error")
}
else
{
res.status(204).send()
}
});
});
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
module.exports.app = app;
module.exports.schema = bill;
Then I have a javscript dedicated to testing
let assert = require('assert');
let chai = require('chai');
let chaiHttp = require('chai-http');
let serverAndSchema = require('../index');
let server = serverAndSchema.app
let Bill = serverAndSchema.schema
let should = chai.should();
chai.use(chaiHttp);
describe('Bills', function() {
describe('/GET bill', function() {
it('should get the specified bill', function(done) {
let expectedBill = new Bill({
type: "Test Type",
dueDate: "12/3/2018T06:00:00.000Z",
company: "Test Company",
amtDue: "100",
paidStatus: "Test Status"
});
expectedBill.save(function(err, savedBill) {
chai.request(server)
.get('/api/bills/'+savedBill.id)
.end((err, res) => {
res.should.have.status(200);
res.body.should.be.a('object');
res.body.should.have.property('type').eql(savedBill.type)
res.body.should.have.property('dueDate').eql(savedBill.dueDate)
res.body.should.have.property('company').eql(savedBill.company)
res.body.should.have.property('amtDue').eql(savedBill.amtDue)
res.body.should.have.property('paidStatus').eql(savedBill.paidStatus)
res.body.should.have.property('_id').eql(savedBill.id)
done();
})
});
});
});
});
The data is added to my database, but I get this error when I try to run the test:
Uncaught TypeError: Cannot read property 'id' of undefined
at
C:\Users\Martae\Documents\Github\BillTracker\test\bill.js:29:46
Any help with this is appreciated!
When I checked the Bill schema, I found that the issue is caused by your due date format. So, the mongo saved is failed and you got undefined for savedBill and when you try to access id, it throws the error that you got.
Here is the solution:
let expectedBill = new Bill({
type: "Test Type",
dueDate: "2018-03-13T06:00:00.000Z", // change date to standardized format
company: "Test Company",
amtDue: "100",
paidStatus: "Test Status"
});
expectedBill.save(function(err, savedBill) {
const id = savedBill._id; // store id, it is always returned as _id
chai.request(server)
.get('/api/bills/'+id)
.end((err, res) => {
// ...
done();
});
});

node.js post api returns old response

I am using express post api for login a user, the problem is it returns the previous post response.
I dont know what wrong thing I am doing.
Here is my app.js
var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var csrf = require('csurf');
// var lusca = require('lusca');
var db = require('./db.config');
var index = require('./routes/index');
var auth = require('./routes/auth');
var users = require('./routes/users');
var admin = require('./routes/admin');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// 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());
//this or other session management will be required
app.use(session({
secret: 'Qwaszx',
resave: true,
saveUninitialized: true
}));
app.use(express.static(path.join(__dirname, 'public')));
/**
* CSRF
*/
// app.use(lusca({
// csrf: true,
// csp: { /* ... */},
// xframe: 'SAMEORIGIN',
// p3p: 'ABCDEF',
// hsts: {maxAge: 31536000, includeSubDomains: true, preload: true},
// xssProtection: true,
// nosniff: true,
// referrerPolicy: 'same-origin'
// }));
/**
* CSRF Token
*/
app.use(csrf());
app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
res.locals._csrf = req.csrfToken();
next();
});
/**
* Routes
*/
app.use('/', index);
app.use('/auth', auth);
app.use('/users', users);
app.use('/admin', admin);
// 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;
and my auth.js route file is under routes directory which is as below:
where I am posting login and getting old response all the time time I do not quit the server and restart it.
var express = require('express');
var router = express.Router();
var userModel = require('../model/user.model');
var session = require('express-session');
var auth = require('../middleware');
/**
* Get register API
*/
router.get('/register', auth.Auth, function(req, res, next) {
res.render('auth/register', { title: 'Register a new user' });
});
/**
* Post register API
*/
router.post('/register', auth.Auth, function (req, res, next) {
if(req.body.password === req.body.c_password ){ //password match
userModel.create(req.body).then(function (result){//Create user
res.redirect('/auth/login');
}).catch( function (err) {
res.redirect('/auth/register');
});
}
else{
res.redirect('/auth/register');
}
});
/**
* Get login API
*/
router.get('/login', auth.Auth, function (req, res, next) {
res.render('auth/login');
});
/**
* Post login API
*/
router.post('/login', auth.Auth, function (req, res, next) {
userModel.login(JSON.stringify(req.body)).then( function(resp) {
// console.log(resp);
req.session.user = {
user_id : resp.user_id,
user_type : resp.user_type,
};
// res.send(resp);
res.json(resp);
// res.redirect('/auth/login')
}).catch(function (err){
// console.log(err);
res.json(err);
// res.redirect('/auth/login')
});
});
/**
* Logout API
*/
router.get('/logout', function (req, res, next) {
return userModel.logout(req.session.user.user_id).then(function (result) {
// console.log("result = " + result);
delete req.session.user;
res.redirect('/auth/login');
}).catch(function(err){
// console.log(err);
res.redirect('/');
});
});
module.exports = router;
now my model file where I put database interface is user.model.js is uder model directory which is shown below:
var connection = require('../db.config');
var randomstring = require("randomstring");
var passwordHash = require('password-hash');
var q = require('q');
var deferred = q.defer();
model = {};
model.index = index;
model.create = create;
model.show = show;
model.login = login;
model.logout = logout;
model.adminLogin = adminLogin;
module.exports = model;
/**
* Show all users
*/
function index(){
connection.query('SELECT * FROM users as U JOIN logs as L ON U.id = L.user_id WHERE U.user_type != "1" ORDER BY L.id DESC', function(error, response){
if(error) deferred.reject(error);
if(response.length > 0){
// console.log(response);
deferred.resolve(response);
}
else{
deferred.resolve([]);
}
});
return deferred.promise;
}
/**
* Create a new user
*
* #param {*array} data
*/
function create(data){
var hashedPassword = passwordHash.generate(data.password);
var user = {
'email' : data.email,
// 'user_name' : data.user_name,
'mac_add' : data.mac_add,
'password' : hashedPassword,
'verification_code' : randomstring.generate(10),
'_token' : data._csrf,
}
//Check user is already exists or not
connection.query('SELECT * FROM users WHERE email = "' + user.email + '" LIMIT 0,1', function(error, result) {
if(error) {
deferred.reject(error);
}
if(result[0]){
deferred.reject('Email ' + result[0].email + ' is already taken. Please try with another email.');
}
else{
return createUser();
}
});
//Create User
function createUser() {
connection.query('INSERT INTO users SET ? ', user , function (error, response){
if(error) {
console.log(error);
deferred.reject(error);
}
else{
console.log(response);
deferred.resolve(response);
}
});
}
return deferred.promise;
}
/**
* Show user details
*
* #param {*number} id
*/
function show(id){
connection.query('SELECT * FROM users WHERE id = "' + id + '"', function(error, response) {
if(error) deferred.reject(error);
if(response[0]) deferred.resolve(response[0]);
});
return deferred.promise;
}
/**
* Login user using email, password and mac address
*
* #param {* array} data
*/
function login(data){
var userData = JSON.parse(data);
connection.query('SELECT * FROM users WHERE email = "' + userData.email + '" LIMIT 0,1', function(error, response) {
if(error) deferred.reject(error);
//check if user exists
if(response.length > 0){
if(passwordHash.verify(userData.password, response[0].password)){//password matching
// Validate that an address is a mac address
if(response[0].user_type === 0){
console.log(response[0]);
deferred.resolve(response[0]);
// if ( require('getmac').isMac(response[0].mac_add) ) {
// // var res = JSON.parse(result[0]);
// return createLog(response[0].id, response[0].user_type);
// }
// else{
// deferred.reject('Unauthorized System!');
// }
}
// else{
// var result = {
// 'user_id' : response[0].id,
// 'user_type' : response[0].user_type,
// }
// deferred.resolve(result);
// }
}
else{
deferred.reject('Invalid credential');
}
}
else{
deferred.reject('User not found');
}
});
/**
* Create user logs
*
* #param {*numeric} user_id
*/
function createLog(user_id, user_type){
var log = {
'user_id' : user_id,
// 'in_time' : new Date(),
}
result = {
'user_id' : user_id,
'user_type' : user_type,
}
connection.query('INSERT INTO logs SET ? ', log, function(err, resp) {
if(err) deferred.reject(err);
if(resp) deferred.resolve(result);
});
}
return deferred.promise;
}
/**
* Logout out time entry
*
* #param {*number} user_id
*/
function logout(user_id){
//Get row id of current log from logs table
connection.query('SELECT id FROM logs where user_id = "' + user_id + '" ORDER BY id DESC LIMIT 0,1', function(err, resp){
if(err) deferred.reject(err);
if(resp[0]){
// console.log(result[0].id);
return updateLog(resp[0].id); //updating time
}else{
deferred.reject("No logs");
}
});
function updateLog(id){ // update the out time
// var out_time = new Date();
// console.log(out_time);
connection.query('UPDATE logs SET signature = "shift end", status = "1" WHERE id = ' + id, function(error, response) {
if(error) deferred.reject(error);
if(response) deferred.resolve(response);
});
// console.log(query.sql);
}
return deferred.promise;
}
/**
* Admin Login
*
* #param {*array} data
*/
function adminLogin(data){
var userData = JSON.parse(data);
connection.query('SELECT * FROM users WHERE email = "' + userData.email + '" AND user_type = "1" LIMIT 1', function(error, response) {
if(error) deferred.reject(error);
//check if user exists
if(response.length > 0){
if(passwordHash.verify(userData.password, response[0].password)){//password matching
// console.log("admin response = " + response[0]);
deferred.resolve(response[0]);
}
else{
deferred.reject('Invalid Credential');
}
}
else{
deferred.reject('Unauthorized user');
}
});
return deferred.promise
}
Now I want to know what wrong thing I am doing.
If I am hanging the node server and restarting it again then it works fine otherwise it returns same error or success response with the different credentials.
Thanks
Thanks Robert your answer was correct exactly. Thanks so much.
The soulution was to make seperate promise for each and every function.
I was using deferred = q.defer(); at the top of the page as globaly
So I have to remove it from here and put it seperately in each function.
Like
function index(){
deferred = q.defer();
....
......
return deferred.promise;
}
this was the correct solution thanks alot robert
Thanks

Node JS body-parser-xml Not Working

I want to handle both JSON- and XML-type requests, so I am using body-parser-xml in my node application.
My problem is the second XML element is not binding to req.body, but I get the first element value instead.
My code is:
var loopback = require('loopback');
var boot = require('loopback-boot');
var cfenv = require('cfenv');
var bodyParser = require("body-parser");
var cookieParser = require('cookie-parser');
require('body-parser-xml')(bodyParser);
var app = module.exports = loopback();
var appEnv = cfenv.getAppEnv();
app.use(bodyParser.json());
app.use(bodyParser.xml({
limit: '1MB', // Reject payload bigger than 1 MB
xmlParseOptions: {
normalize: true, // Trim whitespace inside text nodes
normalizeTags: false, // Transform tags to lowercase
explicitArray: false // Only put nodes in array if >1
}
}));
app.use(bodyParser.urlencoded({
"extended": true
}));
// boot scripts mount components like REST API
boot(app, __dirname);
app.start = function() {
// start the web server
return app.listen(process.env.PORT || 3000, function() {
console.log("env port" + process.env.PORT);
app.emit('started');
var baseUrl = app.get('url').replace(/\/$/, '');
console.log('Web server listening at: %s', baseUrl);
if (app.get('loopback-component-explorer')) {
var explorerPath = app.get('loopback-component-explorer').mountPath;
console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
}
});
};
// start the server if `$ node server.js`
if (require.main === module) {
app.start();
}
My Routes:
module.exports = function(app) {
var router = app.loopback.Router();
var User = app.models.pusers;
var js2xmlparser = require("js2xmlparser");
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
if (req.get("content-type") !== 'undefined') {
if (req.get("content-type") == 'application/json') {
res.setHeader('content-type', req.get("content-type"));
} else if (req.get("content-type") == 'application/xml') {
res.setHeader('content-type', req.get("content-type"));
}
}
next();
});
app.middleware('initial', function logResponse(req, res, next) {
res.on('finish', function() {});
req.on('end', function(data) {});
req.on('data', function(data) {
// the request was handled, print the log entry
console.log(req.method, req.originalUrl, res.statusCode);
if (req.get("content-type") == 'application/xml') {
console.log("xml data's :" + data);
} else if (req.get("content-type") == 'application/json') {
console.log("json data's :" + data);
}
});
next();
});
function responseHandler(req, res, data) {
if (req.get("content-type") == 'application/json') {
return JSON.stringify(data);
} else if (req.get("content-type") == 'application/xml') {
return js2xmlparser("response", JSON.stringify(data));
} else
return data;
}
router.post('/login', function(req, res) {
var response = {};
console.log(req.body);
console.log(req.body.username);
try {
User.find({
where: {
name: req.body.username
}
}, function(err, data) {
if (err) {
response = {
"error": true,
"message": "Error fetching data"
};
} else {
if (data.length != 0) {
if (data[0].name == req.body.username && data[0].password == req.body.password) {
response = {
"error": false,
"data": "Success"
};
} else {
response = {
"error": false,
"data": "Password is incorrect"
};
}
} else if (data.length == 0) {
response = {
"error": false,
"data": "Username is incorrect"
};
}
}
console.log("Check login");
res.end(responseHandler(req, res, response));
});
} catch (ex) {
console.error("Error while retrive all data from User Model by name", ex);
res.end(responseHandler(req, res, "Error while inserting User Model by name"));
}
});
app.use(router);
}
How can i solve this problem?
I found that if you encapsulate the whole data into a single XML tag, you receive the complete set. For example:
<data>
<username>somename</username>
<password>passwd</password>
</data>
Then access it in node.js as:
req_xml = req.body["data"];
console.log(req_xml["username"]);
console.log(req_xml["password"]);

Data not correctly loaded with Node.js using express.js, fs and handlebars

I am kinda new to Node.js and experienced a strange behavior in my application.
At the beginning I am reading all uploaded files to my server using fs.readdir. Then the data is getting stored like this:
// Store all files and their data
var uploads = [];
var docData = [];
//read all files when server starts
fs.readdir(dir, function(err, items) {
if(err) {
console.log("Could not read files from directory " + dir);
}
else {
uploads = items;
uploads.forEach(function(item) {
var path = dir + item;
textract.fromFileWithPath(path, function( err, text ) {
if(err) {
console.log("Could not parse file " + path);
}
else {
var val = {
name : item,
data: text
};
docData.push(val);
}
});
});
}
});
So I store on the one hand the raw files and on the other hand the extracted text as json. But it does not load the files properly. It looks like the items are handed out to the frontend before these arrays are set, but I am not sure about this problem. The data is given to the frontend in this way:
app.get('/:search', function(req, res){
var result = [];
var invalidItems = 0;
for (var i = 0; i < docData.length; i++) {
if(!(stringStartsWith(docData[i].name,"."))) {
var index = i + 1 - invalidItems;
result.push({id: index, doc: docData[i].name, count: 3});
}
else{
invalidItems++;
}
}
res.send(result);
});
And the handlebars template using jade looks like this:
// Template for search results
script#result-template(type='text/x-handlebars-template')
table#data.table.table-striped.table-bordered
thead
tr
th ID
th Document
th Count
th Delete
tfoot
tr
th ID
th Document
th Count
th Delete
tbody
| {{#each this}}
tr
td {{id}}
td
a(href="/uploads/{{doc}}") {{doc}}
td {{count}}
td
span.glyphicon.glyphicon-trash
| {{/each}}
Is there any "clear" way to ensure that all the uploaded data has been parsed before sending the result to the frontend or do you think there is another stupid mistake?
Edit: The call in the js looks like that:
var needle = $('input[name=srch-term]').val();
$.ajax({
url: "http://localhost:1234/"+needle,
type: 'GET',
success: function (resp)
var source = $("#result-template").html();
var template = Handlebars.compile(source);
$("#result").html(template(resp));
},
error: function(e) {
alert('Error: '+e.text);
}
});
The complete app.js looks like this:
var express = require('express');
var path = require('path');
var http = require('http');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var elasticsearch = require('elasticsearch');
var multer = require("multer");
var fs = require('fs');
var textract = require('textract');
var app = express();
var upload = multer({ dest : './public/uploads'});
var dir = './public/uploads/';
// Store all files and their data
var uploads = [];
var docData = [];
//read all files when server starts
fs.readdir(dir, function(err, items) {
if(err) {
console.log("Could not read files from directory " + dir);
}
else {
uploads = items;
uploads.forEach(function(item) {
var path = dir + item;
textract.fromFileWithPath(path, function( err, text ) {
if(err) {
console.log("Could not parse file " + path);
}
else {
var val = {
name : item,
data: text
};
docData.push(val);
}
});
});
}
});
require('dotenv').load();
var client = new elasticsearch.Client({
host: process.env.ES_HOST,
log: 'trace'
});
// 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(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use(multer({ dest: './public/uploads/',
rename: function (fieldname, filename) {
//add the current date to the filename to allow multiple uploads
return filename + Date.now();
},
onFileUploadStart: function (file) {
console.log(file.originalname + ' is starting ...');
},
onFileUploadComplete: function (file) {
console.log(file.fieldname + ' uploaded to ' + file.path);
//add the uploaded file to the stored files
uploads.push(file);
textract.fromFileWithPath(file.path, function( error, text ) {
if(error) {
console.log("Could not parse file " + file.path);
}
else {
//add the uploaded file's text to the docData
var len = dir.length - 2;
var val = {
name : file.path.substring(len),
data: text
};
docData.push(val);
}
});
}
}));
app.post('/upload',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.redirect('/');
});
});
app.get('/:search', function(req, res){
var result = [];
var invalidItems = 0;
console.log("Data = " + docData.length);
for (var i = 0; i < docData.length; i++) {
if(!(stringStartsWith(docData[i].name,"."))) {
var index = i + 1 - invalidItems;
result.push({id: index, doc: docData[i].name, count: 3});
}
else{
invalidItems++;
}
}
console.log("data; " + docData.length);
res.send(result);
});
// 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(process.env.SRV_PORT);
module.exports = app;
function stringStartsWith (string, prefix) {
var res;
try {
res = string.slice(0, prefix.length) == prefix;
}
catch(err) {
res = false;
}
return res;
}

Why I get a null or [ ] response from my server.js file?

I have been doing an example based on the TV showTracker and So far I couldn't get any shows into my website. I have been trying so hard to whether I have made a mistake but I still couldn't find anything. So How to I retrieve these information. I have stared this server.js and mongod in separate CMDs and gulp in another CMD I still couldn't get any of the shows. When I see the responses it will show a blank array "[]" like this. So any advice? Help would be most appreciated. (I have host the website yet, thought this would help also to my question). The error in the net debugger says api/shows/ - response = [ ]
Here is my server.jsrespone
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var showSchema = new mongoose.Schema({
_id: Number,
name: String,
airsDayOfWeek: String,
airsTime: String,
firstAired: Date,
genre: [String],
network: String,
overview: String,
rating: Number,
ratingCount: Number,
status: String,
poster: String,
subscribers: [{
type: mongoose.Schema.Types.ObjectId, ref: 'User'
}],
episodes: [{
season: Number,
episodeNumber: Number,
episodeName: String,
firstAired: Date,
overview: String
}]
});
var userSchema = new mongoose.Schema(
{
email: { type: String, unique: true },
password: String
});
userSchema.pre('save', function (next) {
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(10, function (err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function (err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function (candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function (err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
}
var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);
mongoose.connect('localhost');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
app.get('/api/shows', function (req, res, next) {
var query = Show.find();
if (req.query.genre) {
query.where({ genre: req.query.genre });
} else if (req.query.alphabet) {
query.where({ name: new RegExp('^' + '[' + req.query.alphabet + ']', 'i') });
} else {
query.limit(12);
}
query.exec(function (err, shows) {
if (err) return next(err);
res.send(shows);
});
});
app.get('/api/shows/:id', function (req, res, next) {
Show.findById(req.params.id, function (err, show) {
if (err) return next(err);
res.send(show);
});
});
app.post('/api/shows', function (req, res, next) {
var apiKey = 'E36B52F7E036AFF3';
var seriesName = req.body.showName
.toLowerCase()
.replace(/ /g, '_')
.replace(/[^\w-]+/g, '');
var parser = xml2js.Parser({
explicitArray: false,
normalizeTags: true
});
async.waterfall([
function (callback) {
request.get('http://thetvdb.com/api/GetSeries.php?seriesname=' + seriesName, function (error, response, body) {
if (error) return next(error);
parser.parseString(body, function (err, result) {
if (!result.data.series) {
return res.send(404, { message: req.body.showName + ' was not found.' });
}
var seriesId = result.data.series.seriesid || result.data.series[0].seriesid;
callback(err, seriesId);
});
});
},
function (seriesId, callback) {
request.get('http://thetvdb.com/api' + apiKey + '/series/' + seriesId + '/all/en.xml', function (error, response, body) {
if (error) return next(error);
parser.parseString(body, function (err, result) {
var series = result.data.series;
var episodes = result.data.episode;
var show = new Show({
_id: series.id,
name: series.seriesname,
airsDayOfWeek: series.airs_dayofweek,
airsTime: series.airs_time,
firstAired: series.firstaired,
genre: series.genre.split('|').filter(Boolean),
network: series.network,
overview: series.overview,
rating: series.rating,
ratingCount: series.ratingcount,
runtime: series.runtime,
status: series.status,
poster: series.poster,
episodes: []
});
_.each(episodes, function (episode) {
show.episodes.push({
season: episode.seasonnumber,
episodeNumber: episode.episodenumber,
episodeName: episode.episodename,
firstAired: episode.firstaired,
overview: episode.overview
});
});
callback(err, show);
});
});
},
function (show, callback) {
var url = 'http://thetvdb.com/banners/' + show.poster;
request({ url: url, encoding: null }, function (error, response, body) {
show.poster = 'data:' + response.headers['content-type'] + ';base64,' + body.toString('base64');
callback(error, show);
});
}
], function (err, show) {
if (err) return next(err);
show.save(function (err) {
if (err) {
if (err.code == 11000) {
return res.send(409, { message: show.name + ' already exists.' });
}
return next(err);
}
res.send(200);
});
});
});
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) next();
else res.send(401);
};
app.use(function (req, res, next) {
if (req.user) {
res.cookie('user', JSON.stringify(req.user));
}
next();
});
app.get('*', function (req, res) {
res.redirect('/#' + req.originalUrl);
})
app.use(function (err, req, res, next) {
console.error(err.stack);
res.send(500, { message: err.message });
});
Change var query = Show.find(); in /api/shows to
var query = Show.find(function(err, showdata){
// all the checking and the res.send(shows) goes here
})
Just wait for data and do all the operation(asynchronous)
OK Guys, I finally found the answer to the question. It's nothing wrong with the script (server.js). It is because I think it cannot hold the data in the database ('localhost:27017/test'). That is why maybe I'm getting a null response from the TVDB API. Once I changed my database and connect strings to (
'mongodb://nixsiow:abcd1234#ds027479.mongolab.com:27479/nixshowtrackrapp'
, It worked like a charm.
So maybe my answer may not explain this properly, or you can look for more details in stack overflow. Thanks for the help guys. I hope that this will help who try to do this tutorial and get stuck on this step.
So final Answer:
mongoose.connect('mongodb://nixsiow:abcd1234#ds027479.mongolab.com:27479/nixshowtrackrapp');
var agenda = require('agenda')({ db: { address: 'mongodb://nixsiow:abcd1234#ds027479.mongolab.com:27479/nixshowtrackrapp' } });
Also Nixsow's website may have a help, it is the most recent update that I found for this tutorial.

Categories

Resources