Stormpath wth Openshift has bad route - openshift

This setup is as follows:
Openshift gear with a nodejs component. npm install express body-parser express-stormpath --save. Server will run if you comment out the Stormpath calls/usage.
#!/bin/env node --harmony
// File: server.js
var fs = require('fs');
var express = require('express');
var bparser = require('body-parser');
var stormpath = require('express-stormpath');
var app = express();
// Log access URLs
app.use(function (req, res, next) {
console.log(req.url);
next();
});
// Default response
app.get('/', function(req, res){
res.send('<h2>Ghostfacers</h2>');
});
// Stormpath ApiKey,Secrct,etc set in environment
var baseFile = __dirname + '/index.html';
app.use(stormpath.init(app, {
web: {
spa: { enabled: true, view: baseFile }
}
}));
var port = process.env.OPENSHIFT_NODEJS_PORT;
var addr = process.env.OPENSHIFT_NODEJS_IP;
app.on('stormpath.ready',function() {
app.listen(port,addr, function() {
console.log('%s: Started %s:%d ...',
Date(Date.now() ),addr,port);
});
});
Errors in the nodejs log:
TypeError: Property 'route' of object function router(req, res, next) {
router.handle(req, res, next);
} is not a function at Function.proto.(anonymous function) [as get]...
...
lib/router/index.js:509:22
at addGetRoute ... lib/stormpath.js:137:14

After a good nights sleep and a cup of coffee I was able to get past this issue by using express version 4.x instead of version 3.x. I will submit a ticket to Stormpath to state this dependency.

Related

Whe aren't my subpages visible with nodejs?

I am making simple node app for my website.
I've configured my app.js, controllers and routers so far.
My problem is I keep getting error 404 on two from three subpages, index works fine also. I think they're pretty much the same construction-wise, I've tried tracing app-route-controller but seems good to me.
My console output:
GET / 304 1.443 ms - -
GET /css/style.css 304 0.325 ms - -
GET /images/IMG_2202.png 304 0.639 ms - -
GET /images/vertabelo-tabele.png 304 0.774 ms - -
GET /sprzet 200 1.904 ms - 3241
GET /css/style.css 304 0.393 ms - -
GET /images/IMG_2202.png 304 0.501 ms - -
GET /zamowienia 404 1.152 ms - 1393
GET /wysylka 404 0.917 ms - 1393
As you can see /zamowienia and /wysylka are not found. However the structure is the same as for sprzet.
My app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
const sprzetRouter = require('./routes/sprzetRoute');
const wysylkaRouter = require('./routes/wysylkaRoute');
const zamowieniaRouter = require('./routes/zamowieniaRoute');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/sprzet', sprzetRouter);
app.use('/list-wys', wysylkaRouter);
app.use('/list', zamowieniaRouter);
// 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;
wysylkaRoute
const express = require('express');
const router = express.Router();
const wysylkaController = require('../controllers/wysylkaController');
router.get('/', wysylkaController.showWysylkaList);
router.get('/add', wysylkaController.showAddWysylkaForm);
router.get('/details/:wysId', wysylkaController.showWysylkaDetails);
module.exports = router;
and wysylkaController
const { Router } = require("express");
exports.showWysylkaList = (req, res, next) => {
res.render('pages/wysylka/list-wys', {
navLocation: 'wys'
});
}
exports.showAddWysylkaForm = (req, res, next) => {
res.render('pages/wysylka/form-wys', {
navLocation: 'wys'
});
}
exports.showWysylkaDetails = (req, res, next) => {
res.render('pages/wysylka/list-wys-details', {
navLocation: 'wys'
});
}
My nav also seems fine:
<nav>
<ul>
<li>Strona główna</li>
<li>Zamówienia</li>
<li>Sprzęt</li>
<li>Wysylka</li>
</ul>
</nav>
I've tried backtracing all my paths and comparing /wysylka and /zamowienia to /sprzet but they all seem built the same way.
The problem were wrong endpoints in the app.js.
I had to switch this:
app.use('/', indexRouter);
app.use('/sprzet', sprzetRouter);
app.use('/list-wys', wysylkaRouter);
app.use('/list', zamowieniaRouter);
To this:
app.use('/', indexRouter);
app.use('/sprzet', sprzetRouter);
app.use('/wysylka', wysylkaRouter);
app.use('/zamowienia', zamowieniaRouter);
For endpoints to point to the subfolders instead of specific files.

Loopback Applications Functions Errors

I am developing vuejs applications by using loopback and mysql . when i run the applications I got errors is
app.start is not functions .
here is my code server.js ..
// Copyright IBM Corp. 2016. All Rights Reserved.
// Node module: loopback-workspace
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
module.exports = function(app) {
// Install a "/ping" route that returns "pong"
app.get('/ping', function(req, res) {
res.send('pong');
});
};
// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;
// start the server if `$ node server.js`
if (require.main === module)
app.start();
});
Here is my route.js file code
'use strict';
module.exports = function(app) {
var router = app.loopback.Router();
router.get('/ping', function(req, res) {
res.send('pongaroo');
});
app.use(router);
};
All the server.js file should contain a function called app.start. In this function only the server get started. In the server.js file try to add app.start(), hope that will solve your issue. Refer below pease of code for the app.start function.
app.start = function() {
// start the web server
return app.listen(function() {
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);
}
});
};

node js res Cannot GET /

I launch the Ubuntu on EC2 and running the app on port 80 using nginx. I am trying to exact the data using RESTful get from json "http://data.fixer.io/api/latest?access_key=xxx" and render a table. However, Cannot GET / pops out.
The following code is workable:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('HEY!')
})
app.listen(3000, () => console.log('Server running on port 3000'))
But my code doesnt work.
var request = require("request");
var EventEmitter = require("events").EventEmitter;
var body = new EventEmitter();
request("http://data.fixer.io/api/latest?access_key=xxx", function(error, response, data) {
body.data = data;
body.emit('update');
});
body.on('update', function () {
console.log(body.data);
});

nodejs - stub module.exports functions with sinon

I have an expressjs app with the following routes and middleware modules. I am trying to test the routes module using mocha, chai, http-chai and sinonjs.
The API uses mysql and in order to test the routes module, I have it all modularized so that I can stub out the mysql module.
However when I try to stub middleware/index, I am having trouble. If I try to require index normally, the module doesn't actually get stubbed. If I try to require it using require.cache[require.resolve('./../../lib/routes/middleware/index')];, it seems to stub something, but indexStub.returns(indexObj) returns an error TypeError: indexStub.returns is not a function and TypeError: indexStub.restore is not a function.
How do I stub out index.js properly in order to control the code flow and keep it from trying to connect to mysql?
routes.js
'use strict';
const express = require('express');
const router = express.Router();
const configs = require('./../config/configs');
const middleware = require('./middleware/index');
const bodyParser = require('body-parser');
const useBodyParserJson = bodyParser.json({
verify: function (req, res, buf, encoding) {
req.rawBody = buf;
}
});
const useBodyParserUrlEncoded = bodyParser.urlencoded({extended: true});
// creates a new post item and return that post in the response
router.post('/posts', useBodyParserUrlEncoded, useBodyParserJson, middleware.validatePostData, middleware.initializeConnection, middleware.saveNewPost, middleware.closeConnection, function(req, res) {
if (res.statusCode === 500) {
return res.send();
}
if (res.statusCode === 405) {
return res.send('Item already exists with slug ' + req.body.slug + '. Invalid method POST');
}
res.json(res.body).end();
});
module.exports = router;
middleware/index.js
'use strict';
const configs = require('./../../config/configs');
const database = require('./../../factories/databases').select(configs.get('STORAGE'));
const dataV = require('./../../modules/utils/data-validator');
module.exports = {
initializeConnection: database.initializeConnection, // start connection with database
closeConnection: database.closeConnection, // close connection with database
saveNewPost: database.saveNewPost, // creates and saves a new post
validatePostData: dataV.validatePostData, // validates user data
};
spec-routes.js
'use strict';
var chai = require('chai');
var chaiHttp = require('chai-http');
var sinonChai = require("sinon-chai");
var expect = chai.expect;
var sinon = require('sinon');
chai.use(sinonChai);
chai.use(chaiHttp);
var app = require('./../../app');
describe('COMPLEX ROUTES WITH MIDDLEWARE', function() {
var indexM = require.cache[require.resolve('./../../lib/routes/middleware/index')];
describe('POST - /posts', function() {
var indexStub,
indexObj;
beforeEach(function() {
indexStub = sinon.stub(indexM);
indexObj = {
'initializeConnection': function(req, res, next) {
return next();
},
'closeConnection': function(req, res, next) {
return next();
},
'validatePostData': function(req, res, next) {
return next();
}
};
});
afterEach(function() {
indexStub.restore();
});
it('should return a 500 response', function(done) {
indexObj.saveNewPost = function(req, res, next) {
res.statusCode = 500;
return next();
};
indexStub.returns(indexObj);
chai.request(app)
.post('/posts')
.send({'title': 'Hello', 'subTitle': 'World', 'slug': 'Example', 'readingTime': '2', 'published': false})
.end(function(err, res) {
expect(res).to.have.status(500);
done();
});
});
});
});
You don't use Sinon at all, as it doesn't deal with module loading at all. I see you have started doing this manually using the internal Node API's, but I suggest you do it the way we advise in the Sinon docs regarding this usecase: juse use proxyquire.
It enables you to substitute require calls to ./middleware/index.js for a mock object of your own liking (possibly made using sinon).
You would use it something like this:
var myIndex = {
initializeConnection: sinon.stub(),
closeConnection: sinon.stub(),
saveNewPost: sinon.stub()
};
var app = proxyquire('./../../app', {'./middleware/index': myIndex});

Connecting to MongoDB using Express

I am having trouble understanding what needs to be done in order to connect to MongoDB so i can insert an Object into the database. I am new to using Express as well as MongoDB and don't have a full grasp on the both of them yet.
My app.js which was created using the standard Express setup is as follows.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var ex_session = require('express-session');
var dateformat = require('dateformat');
var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/contacts'
var index = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
// 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;
My index.js is as follows and what i would like to happen is when a post request is made from /mailer, a connection is made to the MongoDB in order to set up for an insert.
var express = require('express');
var router = express.Router();
var url = 'mongodb://localhost:27017/contacts';
var contacts;
/* GET home page. */
var start = function(req, res, next){
console.log("Starting!");
res.render('mailer',{});
}
router.get('/', start);
router.get('/mailer', start);
/* Post mailer Page insert into database*/
router.post('/mailer', function(req, res, next){
res.render('thanks');
console.log("Welcome to the Thank You Page");
MongoClient.connect(url, function(err, db){
if(err == NULL){
console.log("Connected to database");
// parse the body of the page and set up object to send to the
// database
}
});
});
router.get('/contact', function(req, res){
res.render('contact', {});
})
module.exports = router;
*for express ,
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DB_USERNAME+':'+DB_PASSWORD+'#'+DB_HOST+':'DB_PORT+'/'+DB_NAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server for express
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DB_HOST+':'+DB_PORT+'/'+DB_NAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
Your code is super mess,I can show your my configuration and u can refer to.
db.js
import mongoose from 'mongoose';
export default function connectDB() {
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/contacts');
mongoose.connection.once('open', function () {
console.log('mongodb connected.');
});
};
app.js
import connectDB from "db.js";
connectDB();
user.model.js
import mongoose from 'mongoose';
const schema = mongoose.Schema({
email: {type: String, required: true},
mobile: {type: String},
password: {type: String, required: true},
});
const User = mongoose.model('User', schema, 'user');
export default User;
then in your router file u can call User.find() or User.update or ...