-> this is my server.js. while i am trying to open it by using node server, it is showing cannot get/.
-> as i am trying to open. it is showing cannot get/. I have routed all the links correctly. but still this issue is pertaining me.
-> in my server it is showing mongodb connected and running. but whilw i open it it is showing cannot get/
var express = require('express');
var bodyParser = require('body-parser');
var User = require('./app/models/user');
var app = express();
var jwt = require('jwt-simple') var _ = require('lodash') var bcrypt = require('bcrypt')
app.use(bodyParser.json()); // support json encoded bodies app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
var secretkey = "supersecretkey"
app.post('/session', function(req, res, next) {
console.log(req.body.username);
User.findOne({
username: req.body.username
}).select('password').exec(function(err, user) {
if (err) {
return next(err)
}
if (!user) {
return res.send(401)
}
bcrypt.compare(req.body.password, user.password, function(err, valid) {
if (err) {
return next(err)
}
if (!valid) {
return res.send(401)
} //var test = {username:user.username}; //console.log(user.username); var token = jwt.encode({ username: req.body.username}, secretkey) res.json(token)
})
})
})
app.get('/user', function(req, res, next) {
var token = req.headers['x-auth'] console.log(token)
var auth = jwt.decode(token, secretkey)
//console.log(auth)
User.findOne({ username: auth.username
}, function(err, user)
{ res.json(user) }) })
app.post('/user', function(req, res) {
var user = new User({
username: req.body.username
}) bcrypt.hash(req.body.password, 10, function(err, hash) {
user.password = hash user.save(function(err, user) {
if (err) {
throw next(err)
} // res.send(201) res.json(user); }) })
})
app.listen(3000)
->This is my app.js.
"use-strict"
var express = require('express');
var router = express.Router(); // get an instance of the express Router
var morgan = require('morgan');
var bodyParser = require('body-parser');
var app = express();
/*app.use(morgan('dev'));*/
app.use('/public/app/controllers/routes', router);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({
extended: true
})); // support encoded bodies
app.use(require('./config/auth'))
app.use('/api/users', require('./app/controllers/api/users'))
app.use('/api/sessions', require('./app/controllers/api/sessions'))
app.use('/api/products', require('./app/controllers/api/products'))
app.use('/api/companies', require('./app/controllers/api/companies'))
app.use('/api/stockists', require('./app/controllers/api/stockists'))
app.use('/api/employees', require('./app/controllers/api/employees'))
app.use('/api/sales', require('./app/controllers/api/sales'))
app.use('/', require('./app/controllers/static'))
var port = process.env.PORT || 3000
var server = app.listen(port, function() {
console.log('App listening at the ', port);
});
require('./websockets').connect(server)
-> as i am trying to open. it is showing cannot get/. I have routed all the links correctly. but still this issue is pertaining me.
-> in my server it is showing mongodb connected and running. but whilw i open it it is showing cannot get/
Related
many hours spent on reading books, passport.org and similar issues in stackoverflow. However, still had no clue why login failed using passport to authenticate with simple local strategy of username and password. passport.autheticate came back stating with info="missing credential" and user='false".
before stepping into passport.authenticate, confirmed that req.body had the right user info of username and password from Angular.
Besides, user registration using passport worked, however, using same username and password was not able to log in.
Below pls find code and thanks for any help in advance.
App.js (code associated with user registration and login)
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var logger = require('morgan');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var authenticate = require('./lib-general/authenticate');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var User = require('./model/user');
var app = express();
const util = require('util');
var debug = require('debug')('http'),
http = require('http'),
name ='pIn3-server';
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use( bodyParser.urlencoded({ extended: true }) );
app.use(session({
name: 'session-id',
secret: config.secretKey,
saveUninitialized: false,
resave: false,
store: new FileStore()
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', indexRouter);
app.use('/', usersRouter);
authenticate.js
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../model/user');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var jwt = require('jsonwebtoken'); // used to create, sign, and verify tokens
var config = require('../config.js');
passport.use(new LocalStrategy(User.authenticate(),{passReqToCallback : true}));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
console.log("before getToken");
exports.getToken = function(user) {
return jwt.sign(user, config.secretKey,
{expiresIn: 3600});
};
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
console.log("after jwtFromRequest - extract JWT");
console.log(opts.jwtFromRequest);
opts.secretOrKey = config.secretKey;
console.log("after secretOrKey");
console.log(opts.secretOrKey);
exports.jwtPassport = passport.use(new JwtStrategy(opts,
(jwt_payload, done) => {
console.log("JWT payload: ", jwt_payload);
User.findOne({_id: jwt_payload._id}, (err, user) => {
if (err) {
return done(err, false);
}
else if (user) {
return done(null, user);
}
else {
return done(null, false);
}
});
}));
exports.verifyUser = passport.authenticate('jwt', {session: false});
Users.js (user router)
var express = require('express');
const bodyParser = require('body-parser');
var User = require('../model/user');
var passport = require('passport');
var authenticateMy = require('../lib-general/authenticate'); // use my to distinguish from passport authenticate
var LocalStrategy = require('passport-local').Strategy;
var cors = require('./cors');
var userRouter = express.Router();
userRouter.use(bodyParser.json());
const mongoose = require('mongoose');
const mongooseClient = require('mongoose'); /* this is important */
console.log("step into router users");
/*ensure if it from right port of whitelist in cors:3000, 3443, 4200 */
userRouter.options('*', cors.corsWithOptions, (req, res) => { res.sendStatus(200); } )
/* Get users listing. */
userRouter.get('/',cors.cors,function(req,res,next){
res.send('respond with a resource')
});
userRouter.post('/signup', cors.corsWithOptions,(req, res, next) => {
console.log('2.0.0.1 - at register',req.body);
let newUser = new User( {
_id: new mongoose.Types.ObjectId(),
username: req.body.username,
password: req.body.password,
firstName: req.body.firstName,
lastName: req.body.lastName,
role: req.body.role,
remember: req.body.remember }); // from book
User.register(newUser, req.body.password, (err, user) => {
if(err) {
console.log('2.0.0.2 - at register',err,user);
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
}
else {
console.log('2.0.1 - at register',req.body);
user.save((err, user) => {
if (err) {
res.statusCode = 500;
res.setHeader('Content-Type', 'application/json');
res.json({err: err});
return ;
}
passport.authenticate('local')(req, res, () => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Registration Successful!'});
});
});
}
});
});
userRouter.post('/login', cors.corsWithOptions, (req, res, next) => {
console.log('2.0.4 - at login',req.body);
passport.authenticate('local', (err, user , info) => {
console.log('2.0.5 - at login', user, info);
if (err)
return next(err);
if (!user) {
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({success: false, status: 'Login Unsuccessful!', err: info});
}
req.logIn(user, (err) => {
if (err) {
console.log('2.0.6 - at req.login',user);
res.statusCode = 401;
res.setHeader('Content-Type', 'application/json');
res.json({success: false, status: 'Login Unsuccessful!', err: 'Could not log in user!'});
}
var token = authenticateMy.getToken({_id: req.user._id});
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json({success: true, status: 'Login Successful!', token: token});
});
}) (req, res, next);
});
userRouter.get('/logout', (req, res) => {
console.log('in userRouter logout code')
if (req.session) {
req.session.destroy();
res.clearCookie('session-id');
res.redirect('/');
}
else {
console.log('in userRouter log out ')
var err = new Error('You are not logged in!');
err.status = 403;
next(err);
}
});
Body parsing isn't passing any data when i use postman to make a request. When i use the console.log to view the req.body it gives an empty object.. Any ideas why this is happening
Thanks
const app = require('express')();
const morgan = require('morgan');
const mongoose = require('mongoose');
const User = require('./models/user');
const bodyParser = require('body-parser');
const uri = 'mongodb://localhost:27017/amazon';
mongoose.connect(uri, function(err) {
if (err) throw err;
console.log('Connected to the DB');
})
const port = process.env.PORT || 3000;
// Middlewares
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', (req, res) => {
res.json('Hellow');
});
app.post('/create-user', function(req, res, next) {
console.log(req.body);
let user = new User();
user.profile.name = req.body.name;
user.password = req.body.password;
user.email = req.body.email;
user.save(function(err) {
if (err) return next(err);
res.json('Successfully created user ' + user.profile.name);
})
})
app.listen(port, function(err) {
if (err) throw err
console.log('Server running');
});
Postman request should look similar to this image attached
Adding Content-Type : "application/x-www-form-urlencoded" should resolve ur issue.
I'm currently trying to get a node.js/express tutorial working (from Express in Action), but haven't been able to access a mongoose model properly. I call the module in a var called "User" I keep getting the error that "User.find is not a function."
Here is the models/user.js file:
var
bcrypt = require("bcrypt-nodejs"),
mongoose = require("mongoose"),
SALT_FACTOR = 10
;
var noop = function() {};
var userSchema = mongoose.Schema({
displayName: String,
bio: String
});
userSchema.pre("save", function(done) {
var user = this;
if (!user.isModified("password")) {
return done();
}
bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
if (err) { return done(err); }
bcrypt.hash(user.password, salt, noop, function(err, hashedPassword) {
if (err) { return done(err); }
user.password = hashedPassword;
done();
});
});
});
userSchema.methods.checkPassword = function(guess, done) {
bcrypt.compare(guess, this.password, function(err, isMatch) {
done(err, isMatch);
});
};
userSchema.methods.name = function() {
return this.displayName || this.username;
};
var User = mongoose.model("User", userSchema);
module.exports = User;
Here is the routes.js file calling it:
var
express = require("express"),
mongoose = require("mongoose"),
flash = require("connect-flash"),
passport = require("passport"),
router = express.Router()
;
var User = ("./models/user");
router.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.errors = req.flash("error");
res.locals.infos = req.flash("info");
next();
});
router.get("/", function(req, res, next) {
User.find({}, function(err, users) {
assert.equal(err, null);
res.json(users);
});
});
/*
Original route, also doesn't work
router.get("/", function(req, res, next) {
User.find()
.sort({ createdAt: "descending" })
.exec(function(err, users) {
if (err) { return next(err); }
res.render("index", { users: users });
});
});
*/
module.exports = router;
Lastly here's the index.js file, in case it's relevant
var
http = require("http"),
path = require("path"),
express = require("express"),
flash = require("connect-flash"),
session = require("express-session"),
cookieParser = require("cookie-parser"),
logger = require("morgan"),
liquid = require("shopify-liquid"),
bodyParser = require("body-parser"),
mongoose = require('mongoose')
;
var routes = require('./routes');
var app = express();
mongoose.connect('mongodb://localhost:27017/test');
app.set("port", process.env.PORT || 3000);
var engine = liquid({
root: __dirname, // for layouts and partials
extname: '.liquid'
});
app.engine('liquid', engine.express());
app.set('views', ['./views', './views/partials', './views/layouts']);
app.set('view engine', 'liquid');
var assetsPath = path.resolve(__dirname, "assets");
app.use("/assets", express.static(assetsPath));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: "TKRv0IJs=HYqrvagQ#&!F!%V]Ww/4KiVs$s,<<MX",
resave: true,
saveUninitialized: true
}));
app.use(flash());
app.use(routes);
app.use(logger("dev"));
app.use(function(request, response) {
response.status(404).render("404");
});
http.createServer(app).listen(3000, function(){
console.log('App skeleton started on port 3000.');
});
I've tried the solutions suggested from all similar questions but had no luck.
I have some problems with the express session where I cannot retrieve my session variable that I had stored previously. Below are parts of my codes that I had written.
server.js
let express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
cors = require('cors'),
config = require('./config/database'),
expressSession = require('express-session'),
uid = require('uid-safe'),
db;
let app = express();
//Import Routes
let auth = require('./routes/auth'),
chimerListing = require('./routes/chimer-listing'),
brandListing = require('./routes/brand-listing');
//Specifies the port number
let port = process.env.PORT || 3000;
// let port = 3000;
// Express session
app.use(expressSession({
secret: "asdasd",
resave: true,
saveUninitialized: false,
cookie: {
maxAge: 36000000,
secure: false
}
}));
//CORS Middleware
app.use(cors());
//Set Static Folder
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));
//Body Parser Middleware
app.use(bodyParser.json());
//MongoDB
let MongoClient = require('mongodb').MongoClient;
MongoClient.connect(config.database, (err, database) => {
if (err) return console.log(err)
db = database;
//Start the server only the connection to database is successful
app.listen(port, () => {
console.log('Server started on port' + port);
});
});
//Make db accessbile to routers;
app.use(function(req, res, next) {
req.db = db;
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.set('Access-Control-Allow-Headers', 'Content-Type');
next();
});
//Routes
app.use('/login', auth);
app.use('/user-listing', userListing);
app.use('/brand-listing', brandListing);
//Index Route
app.get('/', (req, res) => {
res.send('Invalid Endpoint');
});
genuuid = function() {
return uid.sync(18);
};
auth.js
let express = require('express'),
router = express.Router(),
db;
//Login Router for chimer
router.post('/chimer', (req, res, next) => {
db = req.db;
// let client = req.client;
db.collection('chimeUser').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
//If there is such user
if (docs.length >= 1) {
req.session.chimerId = docs[0]._id;
console.log(req.session);
req.session.save(function(err) {
// session saved
if (err)
console.log(err)
res.json({
success: true,
chimerId: docs[0]._id
//objects: docs
});
})
} else {
res.json({
success: false,
//objects: docs
})
}
});
});
//Login Router brand
router.post('/brand', (req, res, next) => {
db = req.db;
db.collection('brand').find({
Username: req.body.username,
Password: req.body.password
}).toArray().then(function(docs) {
req.session.brand = docs;
console.log(req.session.brand);
//If there is such user
if (docs.length >= 1) {
res.json({
success: true,
//objects: docs
})
} else {
res.json({
success: false,
//objects: docs
})
}
//db.close()
});
});
});
module.exports = router;
user-listing.js
let express = require('express'),
moment = require('moment'),
router = express.Router(),
// ObjectID = require('mongodb').ObjectID,
db, client;
// let applyListing = require('../models/chimer-listing');
//Retrieve All Listing
router.get('/getAllListing', (req, res, next) => {
db = req.db;
console.log(req.session)
db.collection('listing').find().toArray().then(function(listing) {
//If there is any listing
if (listing.length >= 1) {
res.json({
success: true,
results: listing
})
} else {
res.json({
success: false,
})
}
//db.close()
});
});
module.exports = router;
So in my server.js, I have three routes file which is auth, user-listing, and brand-listing.
Firstly, a user will need to login with the web application which is developed in angular2 and this will trigger the auth route. It will then check for the credentials whether does it exist in the database if it exists I will then assign an ID to req.session.chimerId so that in other routes I will be able to use this chimerId.
Next, after the user has logged in, they will then retrieve an item listing. The problem arises where I can't seem to retrieve the req.session.chimerId that I had previously saved. It will be undefined
NOTE: I tried this using Postman and the browser. In the Postman it works, I am able to retrieve back the req.session.chimerId whereas when I use the angular2 application to hit the endpoints req.session.chimerId is always null
I'm having trouble with my server routes, I had the server on heroku but now have it local to debug,
On browser inspection i get
404 (Not Found)
in browser window
Cannot GET /api/auth/register
My server.js
var express = require('express');
var app = express();
var mongoose = require('mongoose');
var logger = require('morgan');
var bodyParser = require('body-parser');
var databaseConfig = require('./config/database');
var router = require('./app/routes');
//CORS middleware
var allowCrossDomain = function(req, res, next) {
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.sendStatus(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
mongoose.connect(databaseConfig.url);
app.listen(process.env.PORT || 8080);
console.log("App listening on port 8080");
app.use(bodyParser.urlencoded({ extended: false })); // Parses urlencoded bodies
app.use(bodyParser.json()); // Send JSON responses
app.use(logger('dev')); // Log requests to API using morgan
router(app);
My routes.js
var AuthenticationController = require('./controllers/authentication'),
ExerciseController = require('./controllers/exercises'),
express = require('express'),
passportService = require('../config/passport'),
passport = require('passport');
var requireAuth = passport.authenticate('jwt', {session: false}),
requireLogin = passport.authenticate('local', {session: false});
module.exports = function(app){
var apiRoutes = express.Router(),
authRoutes = express.Router(),
exerciseRoutes = express.Router();
// Auth Routes
apiRoutes.use('/auth', authRoutes);
//authRoutes.post('/register', AuthenticationController.register);
authRoutes.post('/register', function(req, res){
AuthenticationController.registerUser
});
authRoutes.post('/login', requireLogin, AuthenticationController.login);
authRoutes.get('/protected', requireAuth, function(req, res){
res.sendStatus({ content: 'Success'});
});
// Exercise Routes
apiRoutes.use('/exercises', exerciseRoutes);
exerciseRoutes.get('/', requireAuth, AuthenticationController.roleAuthorization(['client','trainer','admin']), ExerciseController.getExercises);
exerciseRoutes.post('/', requireAuth, AuthenticationController.roleAuthorization(['trainer','admin']), ExerciseController.createExercise);
exerciseRoutes.delete('/:exercise_id', requireAuth, AuthenticationController.roleAuthorization(['trainer','admin']), ExerciseController.deleteExercise);
// Set up routes
app.use('/api', apiRoutes);
}
And my Controller Authentication.js :
var jwt = require('jsonwebtoken');
var User = require('../models/user');
var authConfig = require('../../config/auth');
function generateToken(user){
return jwt.sign(user, authConfig.secret, {
expiresIn: 10080
});
}
function setUserInfo(request){
return {
_id: request._id,
email: request.email,
role: request.role,
trainer: request.trainer,
programs: request.programs
};
}
exports.login = function(req, res, next){
var userInfo = setUserInfo(req.user);
console.log(userInfo)
res.status(200).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
});
}
exports.registerUser = function(req, res, next){
var email = req.body.email;
var password = req.body.password;
var role = req.body.role;
var trainer = req.body.trainer;
var programs= req.body.programs;
if(!email){
return res.status(422).send({error: 'You must enter an email address'});
}
if(!password){
return res.status(422).send({error: 'You must enter a password'});
}
User.findOne({email: email}, function(err, existingUser){
if(err){
return next(err);
}
if(existingUser){
return res.status(422).send({error: 'That email address is already in use'});
}
var user = new User({
email: email,
password: password,
role: role,
trainer: trainer,
programs: programs
});
user.save(function(err, user){
if(err){
return next(err);
}
var userInfo = setUserInfo(user);
res.status(201).json({
token: 'JWT ' + generateToken(userInfo),
user: userInfo
})
});
});
}
exports.roleAuthorization = function(roles){
return function(req, res, next){
var user = req.user;
User.findById(user._id, function(err, foundUser){
if(err){
res.status(422).json({error: 'No user found.'});
return next(err);
}
if(roles.indexOf(foundUser.role) > -1){
return next();
}
res.status(401).json({error: 'You are not authorized to view this content'});
return next('Unauthorized');
});
}
}
I dont have much experience with express/node so im not sure where im going wrong, could be something simple im just not able to see, anyways any help is greatly appreciated , not sure if you need more info, this is going to be the back end for an ionic 2 app