authenticate tp express server tunneled through ngrok - express

I have an express server serving react pages. I am trying to show the work to a client via a ngrok tunnel. But whenever I try to log in at the ngrok URL for my server it fails to connect back to my localhost where the express routes for auth are.
I feel like it's a simple error I'm making. The browser is trying to make a request to the express server at localhost:5000, but there is nothing at localhost on my client's network.
This is my app.js
const createError = require('http-errors');
const express = require('express');
const debug = require('debug')('app');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
require('dotenv').config()
const ensureToken = require('./middleware/ensureToken');
const path = require('path');
const app = express();
const { init } = require('./utils/cron/createCron');
const cors = require('cors')
// Routers
const authRouter = require('./routes/auth')
const botRouter = require('./routes/bot')
const proxyRouter = require('./routes/proxy');
const winstonLogger = require('./utils/log/logger');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
const whiteList = ['http://localhost:3000/', 'http://localhost:3000']
const corsOptions = {
origin: (origin, callback)=>{
if (whiteList.indexOf(origin) !== -1){
callback(null, true)
}else{
callback(new Error('Not Allowed by CORS'))
}
optionsSuccessStatus:200
}
}
// app.use(cors(corsOptions))
app.use(cors({ credentials: true, origin: true }))
app.use(express.static(path.join(__dirname, 'build')));
// Base Routes
app.use('/api/auth', authRouter);
app.use(ensureToken) //Add this before routes that need to be protected ny valid token
app.use('/api/bot', botRouter);
app.use('/api/proxy', proxyRouter);
app.get("*", (req, res) => {
res.sendFile(path.join(__dirname, "../client/build/index.html"));
});
// 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');
});
app.listen(process.env.PORT, ()=>{
winstonLogger.info(`Listening on ${process.env.PORT}`)
debug(`Listening on ${process.env.PORT}`);
console.log(`Listening on ${process.env.PORT}`);
init()
})
module.exports = app;
Any help is appreciated!!

Related

external api results not loading in node.js using https module

whats wrong with my code? its showing no results....although it kinda works when i use google.com as url but in other cases it shows no results*I haven't shared my api key here(appid=)
const express = require('express');
const app = express();
const http = require('http');
app.get("/", function(req, res) {
const url= 'https://api.openweathermap.org/data/2.5/weather?q=london&appid='
http.get(url, function(response){
console.log(response);
// response.on("data", function(data){
// const weatherData = JSON.parse(data);
// const temp = weatherData.main.temp;
// // const weatherDescription = weatherData.weather[0].description;
// res.send(temp)
// })
// res.send('server is sending');
})
})
app.listen(3000, function(req, res){
console.log('Server is alive')
})

Connect flash not displaying messages in Pug

I have an application with several routes, and I want to send flash messages of different kinds given the user interaction: either a success or failure message, or in some cases no message. Right now the messages are not displaying and I can't figure out how to get it to work. I'm using Node, Express and Pug.
I have a server.js file, routes.js file, message.pug file, and layout.pug file. Here are my files:
server.js
// init project
const express = require('express');
const app = express();
const bodyparser = require("body-parser");
const flash = require('connect-flash');
const passport = require("passport");
const session = require("express-session");
// http://expressjs.com/en/starter/static-files.html
app.use(express.static("public"));
app.set('view engine', 'pug');
// bodyparser middleware
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
// express-session middleware
app.use(session({
secret: process.env.SECRET,
resave: true,
saveUninitialized: true
}));
// express-messages middleware
app.use(flash());
app.use((req, res, next) => {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use(express.json());
// import passport-config file
require("./passport-config")(passport);
// passport middleware
app.use(passport.initialize());
app.use(passport.session());
const routes = require('./routes.js');
routes(app);
// listen for requests :)
const listener = app.listen(process.env.PORT, () => {
console.log('Your app is listening on port ' + listener.address().port);
});
routes.js
app.get('/', (req, res) => {
req.flash("success", "your flash messages are working");
res.redirect("/admin");
});
app.get("/admin", (req, res) => {
res.render(process.cwd() + '/views/pug/admin');
});
message.pug
.messages
each type in Object.keys(messages)
each message in messages[type]
div(class="alert alert-" + type) #{ message }
// expected output
// div(class="alert alert-success") your flash messages are working
layout.pug
div.col-10.ml-sm-auto.px-4
!= messages('message', locals)
Since I had only two types of messages I was sending -- success or error -- I got rid of my messages.pug file and used the following code, which works.
server.js
// init project
const express = require('express');
const app = express();
const bodyparser = require("body-parser");
const flash = require('connect-flash');
const passport = require("passport");
const session = require("express-session");
// http://expressjs.com/en/starter/static-files.html
app.use(express.static("public"));
app.set('view engine', 'pug');
// bodyparser middleware
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
// express-session middleware
app.use(session({
secret: process.env.SECRET,
resave: true,
saveUninitialized: true
}));
// express-messages middleware THIS IS WHAT I CHANGED
app.use(flash());
app.use((req, res, next) => {
res.locals.errors = req.flash("error");
res.locals.successes = req.flash("success");
next();
});
app.use(express.json());
// import passport-config file
require("./passport-config")(passport);
// passport middleware
app.use(passport.initialize());
app.use(passport.session());
const routes = require('./routes.js');
routes(app);
// listen for requests :)
const listener = app.listen(process.env.PORT, () => {
console.log('Your app is listening on port ' + listener.address().port);
});
routes.js (the same as before)
app.get('/', (req, res) => {
req.flash("success", "your flash messages are working");
res.redirect("/admin");
});
app.get("/admin", (req, res) => {
res.render(process.cwd() + '/views/pug/admin');
});
Then in layout, I use the following:
div.col-10.ml-sm-auto.px-4
if successes
for success in successes
div.alert.alert-success #{ success }
if errors
for error, i in errors
div.alert.alert-danger #{ error }
This works for displaying a message in a redirect.
Note: If you want to display a message directly (via res.render()), you have to pass it to the render method directly like this:
app.get('/admin', (req, res) => {
req.flash("success", "flash message for a render method");
res.render("/admin", { successes: req.flash("success") });
});

404 on API call in Thinkster MEAN Stack Tutorial

I'm following this Thinkster tutorial on building a reddit-esque web app using MEAN.
The tutorial instructs using curl to create a new post.
C:\root>curl --data "title=test&link=http://test.com" http://localhost:3000/posts
However, I get this error in response:
<h1>Not Found</h1>
<h2>404</h2>
<pre>Error: Not Found
at C:\root\app.js:30:13
at Layer.handle [as handle_request] (C:\root\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\root\node_modules\express\lib\router\index.js:312:13)
at C:\root\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\root\node_modules\express\lib\router\index.js:330:12)
at next (C:\root\node_modules\express\lib\router\index.js:271:10)
at C:\root\node_modules\express\lib\router\index.js:618:15
at next (C:\root\node_modules\express\lib\router\index.js:256:14)
at Function.handle (C:\root\node_modules\express\lib\router\index.js:176:3)
at router (C:\root\node_modules\express\lib\router\index.js:46:12)</pre>
I looked through those files, but all the references were just showing me what happens to the error...
Here's some code
/routes/index.js:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
router.get('/posts', function(req, res, next){
Post.find(function(err,posts){
if(err){ return next(err); }
res.json(posts);
})
})
router.post('/posts', function(req,res,next){
var post = new Post(req.body);
post.save(function(err, post){
if(err){ return next(err); }
res.json(post);
})
})
/models/Posts.js:
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: {type: Number, default: 0},
comments: [{type: mongoose.Schema.Types.ObjectId, ref: 'Comment'}]
});
mongoose.model('Post', PostSchema);
app.js:
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 index = require('./routes/index');
var users = require('./routes/users');
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);
app.use('/users', users);
// 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;
var mongoose = require('mongoose');
require('./models/Posts');
require('./models/Comments');
mongoose.connect('mongod:localhost/news');
I feel like I did everything correct, except I wasn't sure where to place the additional routes in the routes index file, and similarly in app.js. But this seems negligible to me. I performed all the debugging I could think of but am stuck.
It should also be noted that this tutorial was perhaps not intended for use on a Windows machine. I had to install curl and do a few other things that perhaps wouldn't be necessary on a Linux or Mac. I am using Windows 10.
Your module.exports is called prematurely in routes/index.js. Move module.exports = router; to the bottom of your file, recycle your service, and try again.
Also there are issues with app.js. See below:
app.js:
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');
// Notice the differences starting here
var app = express();
var mongoose = require('mongoose');
// connect MongoDB
mongoose.connect('mongodb://localhost/news', function(err,db){
if (!err){
console.log('Connected to /news!');
} else{
console.dir(err); //failed to connect
}
});
require('./models/Posts');
require('./models/Comments');
var index = require('./routes/index');
var users = require('./routes/users');
// 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);
app.use('/users', users);
// 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;
routes/index.js:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/posts', function(req, res, next){
Post.find(function(err,posts){
if(err){
alert(err);
return next(err);
}
res.json(posts);
})
})
router.post('/posts', function(req,res,next){
var post = new Post(req.body);
post.save(function(err, post){
if(err){
alert(err);
return next(err);
}
res.json(post);
})
})
module.exports = router;

Running Ghost module for node.js on Heroku as subdirectory

I'm trying to install Ghost to my node app. I followed the configuration instructions and got it running with, however when I navigate to the blog subdirectory it just shows my site's homepage. I'm passing it the express app instance to start the server. What am I doing wrong?
var ghost = require('ghost');
ghost().then(function (ghostServer) {
app.use(ghostServer.config.paths.subdir, ghostServer.rootApp);
ghostServer.start(app);
});
I read online about running Ghost with ngynx or apache and configuring it to do some kind of proxy thing, but I don't really understand what all that's about.
Here is a working version of app.js for express and ghost subdirectory setup. Notice how your express routes need to be wrapped in the ghost.then() callback.
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 ghost = require('ghost');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
ghost().then(function (ghostServer) {
app.use(ghostServer.config.paths.subdir, ghostServer.rootApp);
ghostServer.start(app);
// 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(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('/', routes);
app.use('/users', users);
// 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: {}
});
});
});
module.exports = app;
const ghost = require('ghost')
const express = require('express')
const path = require('path')
const { getSubDir } = require('./node_modules/ghost/core/server/services/url/utils')
const app = express()
ghost().then((ghostServer) => {
app.use('/games', express.static(path.join(__dirname, 'games')))
app.use(getSubdir(), ghostServer.rootApp)
ghostServer.start(app)
})
latest howto included here:
https://docs.ghost.org/docs/using-ghost-as-an-npm-module

stormpath error If you do not specify a \'requestAuthenticator\' field, y

I'm getting the error specified above when trying to build a express-stormpath app. I'll list the applicable code:
Error: If you do not specify a 'requestAuthenticator' field, you must specify an ApiKey.
at Object.getAuthenticator (d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express- stormpath\node_modules\stormpath\lib\authc\index.js:24:11)
at new RequestExecutor (d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\lib\ds\RequestExecutor.js:37:37)
at new DataStore (d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\lib\ds\DataStore.js:46:52)
at new Client (d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\lib\Client.js:8:21)
at d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\lib\stormpath.js:60:36
at d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\lib\authc\ApiKeyLoader.js:14:14
at d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\node_modules\properties-parser\index.js:348:20
at fs.js:208:20
at Object.oncomplete (fs.js:108:15)
[Updated] server.js
var express = require('express'),
session = require('express-session'),
crypto = require('crypto'),
formidable = require('formidable'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
index = require('./routes/index'),
users = require('./routes/users'),
stormpath = require('express-stormpath'),
config = require('./config/credentials.js'),
app = express();
function hashPwd(pwd) {
return crypto.createHash('sha256').update(pwd).digest('base64').toString();
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(stormpath.init(app, {
apiKeyFile: config.stormpathapi.apiKeyFile,
application: config.stormpathapi.application,
secretKey: config.stormpathapi.secretKey,
sessionDuration: 1000 * 60 * 30
}));
// domains for better error handling
app.use(function(req, res, next){
// create a domain for this request
var domain = require('domain').create();
// handle errors on this domain
domain.on('error', function(err){
console.error('DOMAIN ERROR CAUGHT\n', err.stack);
try {
// failsafe shutdown in 5 seconds
setTimeout(function(){
console.error('Failsafe shutdown.');
process.exit(1);
}, 5000);
// stop taking new requests
server.close();
try {
// attempt to use Express error route
next(err);
} catch(error){
// if Express error route failed, try
// plain Node response
console.error('Express error mechanism failed.\n', error.stack);
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Server error.');
}
} catch(error){
console.error('Unable to send 500 response.\n', error.stack);
}
});
// add the request and response objects to the domain
domain.add(req);
domain.add(res);
// execute the rest of the request chain in the domain
domain.run(next);
});
// cross-site request forgery protection
app.use(require('csurf')());
app.use(function(req, res, next){
res.locals._csrfToken = req.csrfToken();
next();
});
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'client')));
//name: cookie_name,
//store: sessionStore, // connect-mongo session store
app.use(session({
secret: config.cookieSecret,
resave: false,
saveUninitialized: true
}));
app.use('/', index);
app.use('/users', users);
// 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: {}
});
});
module.exports = app;
route index.js
var express = require('express'),
stormpath = require('express-stormpath'),
router = express.Router();
router.get('/', stormpath.groupsRequired(['dataentry']), function(req, res) {
res.render('index', { title: 'Volume Grid Data Entry' });
});
module.exports = router;
Initially the route signature was this but that didn't work either. I will need the ability in the future to base page security on groups...so, I'm not sure if I should use loginRequired or groupsRequired or both :-/
router.get('/', stormpath.loginRequired, function(req, res) {
Thanks!
That code looks correct -- but where is your app.use(require('./index')); code? That will be necessary after the app.use(stormpath.init(...)) stuff above =)
NOTE: I'm the author of the express-stormpath library.
EDIT: Here's a full example:
var express = require('express'),
stormpath = require('express-stormpath'),
router = express.Router();
var app = express();
router.get('/', stormpath.groupsRequired(['dataentry']), function(req, res) {
res.render('index', { title: 'Volume Grid Data Entry' });
});
app.use('/', router);
app.listen(3000);