Bad Request trying to start node server at Azure web app - node.js

I'm trying to run my node server.js there but it's not working.
I have sent all my files over the FTP in a folder called api (wwwroot is my website, so i need to run this server inside api folder).
Do i need to do something else or what?
Here's my server.js code:
//Dependecies
var express = require('express');
var app = express();
var port = process.env.PORT || 3030;
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session')
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var MongoStore = require('connect-mongo')(session);
var cors = require('./cors');
//Database Configurations
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
//Passport Strategies
require('./config/passport')(passport);
//Morgan Logger
app.use(morgan('dev'));
//Cookie Parser
app.use(cookieParser());
//bodyParser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//Session
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true,
cookie: { maxAge: null, secure: false },
store: new MongoStore({
url: configDB.url,
collection: 'sessions'
})
}));
//Connect Flash
app.use(flash());
//CORS Setup
app.use(cors());
//Passport
app.use(passport.initialize());
app.use(passport.session());
//Require the Routes
require('./app/routes.js')(app, passport);
//Start Server
app.listen(port);
console.log('Server is Running!');
EDIT :
When i type in the console, it stops for a bit and print "Bad Request".

Commonly, the 400 BAD request HTTP error code means that the request could not be understood by the server due to malformed syntax. You could check your request url, or post body.
Additionally, you can use the FTP tool to check whether there is a web.config file in your root directory on Azure Web Apps environment. If not, you can manually create one, you can refer to https://tomasz.janczuk.org/2011/08/hosting-express-nodejs-applications-in.html for a sample for an express based application.
Meanwhile, you can refer to https://learn.microsoft.com/en-us/azure/app-service-web/app-service-web-nodejs-best-practices-and-troubleshoot-guide for more info about troubleshooting on node.js applications on Azure Web Apps.
Any further concern, please feel free to let me know.

Related

req.isAuthenticated() returning false all the time in passportjs

I have passport setup in express and req.isAuthenticated() always returning due to wrong order of code in index.js. I am not able to figure out the order in which I have to write code , I searched for other answers in stackoverflow and I couldnt figure out the right order since my code has different dependencies please help . This is my index.js file :
const winston = require("winston");
const express = require("express");
const config = require("config");
const app = express();
const passport = require('passport');
const flash = require('connect-flash');
var session = require('express-session');
const cookieParser = require('cookie-parser');
app.use(express.json());
app.use(cookieParser());
app.use(session({
secret: 'ilovescotchscotchyscotchscotch',
resave: false,
saveUninitialized: true,
cookie: { secure: true }
}));
app.use(passport.initialize());
app.use(passport.session());
require('./services/passport')(passport);
require("./startup/db")();
app.use(flash());
require("./startup/logging")();
require("./startup/cors")(app);
require("./startup/routes")(app);
require("./startup/config")();
//require("./startup/validation")();
const port = process.env.PORT || config.get("port");
const server = app.listen(port, () =>
winston.info(`Listening on port ${port}...`)
);
module.exports = server;
Thanks.

Nodejs Flash messages only loads after the page is refreshed (connect-flash)

I'm getting stuck with connect-flash , all flash messages doesn't load on the page unless I refresh for a couple of times I'm not sure why.
I created a small project just to test connect-flash and it's the same result, please check the code below:
App.js code:
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const flash = require('connect-flash');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
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(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true
}));
//using flash
app.use(flash());
app.use(function(req, res, next){
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
});
//flash route
app.get('/flash', (req, res) =>{
req.flash("success", "CONNECT FLASH TEST");
res.render('flash');
});
const port = process.env.PORT || 5000;
app.listen(port, () =>{
console.log(`App has started on port ${port}`);
})
Here's the code for the flash.hbs page to render the flash message:
<h1>Flash page</h1>
{‌{#if success}}
<h2>{‌{success}}</h2>
{‌{/if}}
Thanks so much in advanced, any help would be highly appreciated guys.
Do they render after just one refresh? That's how they are supposed to work.
"Flash messages" are used to carry a message over to the next request, and most of the time the only reason is the post-request-get pattern. If you just want to show a message to the user on the same page, while not doing a redirect, you don't need a library for it. Just pass the message to the template as data.
I was halfway through rolling my own new version of req.flash, when I was looking through the docs of express-session and came across this gem:
Note Since version 1.5.0, the cookie-parser middleware no longer needs to be used for this module to work. This module now directly reads and writes cookies on req/res. Using cookie-parser may result in issues if the secret is not the same between this module and cookie-parser.
And lo, I had these lines:
app.use(require('cookie-parser')())
const session = require('express-session')
const MongoStore = require('connect-mongo')(session)
app.use(session({
secret: process.env.SESSION_STORE_SECRET,
store: new MongoStore({mongooseConnection: mongoose.connection}),
maxAge: 10*365*24*60*60*1000, // set to 10 years
resave: false,
saveUninitialized: false
}))
Once I changed the cookie-parser line to:
app.use(require('cookie-parser')(process.env.SESSION_STORE_SECRET))`
it worked exactly as expected!
(For some people, the answer will be to remove cookie-parser altogether.)

Implement cookie based authentication in Node JS with Passport

Below is my server.js (app.js). I am using express with passport, for user authentication. But whenever I restart my node server user logsout.
I am very new to nodejs, I was wondering how I could implement a cookie based authentication. So that user does not log out even if the server starts. I'm sure theres some config change which I have not able to find.
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
// configuration ===============================================================
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'yassers' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
Its logout when you restart your start because its stored in MemoryStore(RAM). Use mongoStore to store your session mongodb. Try below code:
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoStore = new MongoStore({
url: 'your mongo db url'
});
app.use(session({
secret: 'your secret',
saveUninitialized: true, // don't create session until something stored
resave: false, //don't save session if unmodified
store: mongoStore,
cookie: {
domain: 'domain name',
maxAge: 1000 * 24 * 60
}
}));

Share sessions with redis and passport on a subdomain?

I am using npm subdomain, inside my app I have routes that fake a subdomain
// looks like app.localhost:3000
router.get('/subdomain/app', app.dashboard);
So I have a login page on a subdomain and a login page on a non subdomain page. They don't share sessions, so I have to login twice. I want to setup redis, but I don't know how.
// here is my session middleware, I tried using .localhost
app.use(session({ secret: 'something', domain: '.localhost', }));
I have seen where people are using redis like
app.use(express.session({
store:new RedisStore({
host: config.redis.session.host,
port: config.redis.session.port,
db: config.redis.session.db
}),
secret: config.session_secret
}));
This seems like it could solve my issue but I have no clue how to setup a redisStore and where the config data comes from?
Can someone explain to me how to use redis so that when a user logs in on either app.example.io or example.io that he/she is logged in for good, no need to log in twice?
You need to require following modules.
connect-redis
express-session
cookie-parser
Then use the following sample code:
var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
var app = express();
app.use(cookieParser());
app.use(session({
secret: "thisismysecretkey",
store: new RedisStore({ host: 'localhost', port: 6379})
}));
app.get('/', function (req, res) {
res.send('Hello World!')
})
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log('Example app listening at http://%s:%s', host, port)
})
Source : How to save and retrieve session from Redis
Here is how I did it, this is the most important piece - domain: .yourdomain.io Make sure to have that preceeding dot before your domain.
var express = require('express'),
app = express(),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
expressSession = require('express-session'),
sessionMiddleware = null,
redis = require('redis'),
conn_redis = {
path: '/var/run/redis/redis.sock',
socket_keepalive: true
}
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
const connectRedis = require('connect-redis')(expressSession),
uid = require('uid-safe').sync
sessionMiddleware = expressSession({
store: new connectRedis(conn_redis),
secret: 'xxxxxxxxxxxxxxxxxxxxx',
name: 'session_name',
resave: false,
rolling: true,
saveUninitialized: false,
logErrors: true,
cookie: {
path: '/',
domain: '.yourdomain.io'
expires: new Date(Date.now() + 3600000),
maxAge: 3600000
}
})

how to create different session on url based in nodejs?

Our site have two section :
1. admin (content management)
2. site
Admin section will have url '/admin' and site section have url '/'.
Example : My site name is www.example.com, then admin section url is "www.example.com/admin" and site url is "www.example.com".
I want to create url based session means request from admin section will have different session than request from site section.
How can i do it?
Assuming you're using express, you can separate your routers for your routes and apply the session middleware to each router.
routes/index.js
var express = require('express'),
router = express.Router(),
session = require('express-session');
router.use(session({
secret: 'index route secret',
resave: false,
saveUninitialized: true
}));
module.exports = router;
routes/admin.js
var express = require('express'),
router = express.Router(),
session = require('express-session');
router.use(session({
secret: 'admin route secret',
resave: false,
saveUninitialized: true
}));
module.exports = router;
app.js
var express = require('express'),
app = express();
app.use('/', require('./routes/index'));
app.use('/admin', require('./routes/admin'));
app.listen(3000);
documentation

Resources