I'm building api for my app and trying to use passport jwt.
I can register new users and login(get the token back) but when I use the Postman to check the "protected" route I can use Any Token like this 'any any'
Pasport.js
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../api/models/user/userModel'),// load up the user model
config = require('../config/database'); // get db config file
module.exports = (passport)=> {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({id: jwt_payload.id}, (err, user)=> {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
Server.js
const express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
morgan = require('morgan'),
passport = require('passport'),
bodyParser = require('body-parser'),
jwt = require('jsonwebtoken'),
config = require('./config/database'),
Event = require('./api/models/event/eventModel'),
User = require('./api/models/user/userModel');
mongoose.Promise = global.Promise;
mongoose.connect(config.database);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(passport.initialize());
/* Routers registration */
const routesEvent = require('./api/routes/event/eventRoutes');
routesEvent(app);
const routesUser = require('./api/routes/user/userRoutes');
routesUser(app);
/* END Routers registration */
/* Express middleware
* which used to return more interactive messages */
app.use((req, res, next)=>{
res.status(404).send({url: req.originalUrl + ' not found'});
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
/* END Express middleware */
// Launch the server on port 3000
const server = app.listen(3000, () => {
const { address, port } = server.address();
console.log(`RESTful API server Listening at http://${address}:${port}`);
});
EventRouter.js
const jwt = require('jsonwebtoken'),
passport = require('passport');
require('../../../config/passport')(passport); // as strategy in ./passport.js needs passport object
module.exports = (app)=> {
const event = require('../../controllers/event/eventController');
// Routes
app.route('/events' )
.get( event.list_all_events, passport.authenticate('jwt', { session: false}));
};
EventController
const mongoose = require('mongoose'),
Event = mongoose.model('Events'),
getToken = require('../../../config/getToken');
exports.list_all_events = (req, res)=> {
let token = getToken(req.headers);
if(token){
Event.find({}, (err, event)=> {
if (err)
res.send(err);
res.json(event);
});
} else {
return res.status(403).send({success: false, msg: 'Unauthorized.'});
}
};
I'm definitely doing something wrong in controller or in this file
GetToken.js
module.exports = getToken = (headers)=> {
console.log(headers);
if (headers && headers.authorization) {
let parted = headers.authorization.split(' ');
//Here I can see my Token from the Postman
if (parted.length === 2) {
return parted[1];
} else {
return null;
}
} else {
return null;
}
};
Please, any ideas about a mistake that I'm making above?
Below line act as an middle ware. It is validating JWT token, once token is validated it will call JwtStrategy and setting user object in request and then it will call the actual function which is suppose to be executed.
passport.authenticate('jwt', { session: false})
You really do not need getToken function. It will be taken care by above line. If token is not validated then above line automatically returns 401.
Looks strange but when I changed code to this
EventRouter.js
app.route('/events' )
.get( passport.authenticate('jwt', { session: false}), event.list_all_events)
.post(event.create_event);
It's works like expected
The only one difference is the order in get(passport, function)
Related
I am working on a chat application where socket is used for bi-directional sharing of messages.
The socket currently works fine but I want to be able to authenticate user before they can have access to the socket connection. I have trying to use passport but it would seem there is something I am not doing right as I get the error No session found.
const createError = require("http-errors");
const express = require("express");
const { join } = require("path");
const logger = require("morgan");
const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");
const session = require("express-session");
const SequelizeStore = require("connect-session-sequelize")(session.Store);
const db = require("./db");
const { User } = require("./db/models");
const passport = require('passport');
// create store for sessions to persist in database
const sessionStore = new SequelizeStore({ db });
const http = require("http");
const db = require("../db");
const onlineUsers = require("../onlineUsers");
const passportSocketIo = require('passport.socketio');
const { json, urlencoded } = express;
const app = express();
app.use(logger("dev"));
app.use(json());
app.use(urlencoded({ extended: false }));
app.use(express.static(join(__dirname, "public")));
app.use(cookieParser());
app.use(session({
genid:(req)=>{
return req.cookies
},
secret: process.env.SESSION_SECRET,
resave: true,
store: sessionStore,
saveUninitialized: true,
}));
app.use(function (req, res, next) {
const token = req.cookies["messenger-token"];
if (token) {
jwt.verify(token, process.env.SESSION_SECRET, (err, decoded) => {
if (err) {
return next();
}
User.findOne({
where: { id: decoded.id },
}).then((user) => {
req.user = user;
return next();
});
});
} else {
return next();
}
});
app.use(passport.initialize());
app.use(passport.session());
const port = normalizePort(process.env.PORT || "3001");
app.set("port", port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces, and sync database.
*/
const io = require("socket.io")(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST", "PUT"],
credentials: true
}
});
io.use(
passportSocketIo.authorize({
cookieParser: cookieParser,
key: 'messenger-token',
secret: process.env.SESSION_SECRET,
store: sessionStore,
success: onAuthorizeSuccess,
fail: onAuthorizeFail
})
);
function onAuthorizeSuccess(data, accept) {
console.log('successful connection to socket.io');
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept) {
if (error) throw new Error(message);
console.log('failed connection to socket.io:', message);
accept(null, false);
}
io.on("connection", (socket) => {
// console.log(`USER ${JSON.stringify(socket)}`);
socket.on("go-online", (id) => {
if (!onlineUsers.includes(id)) {
onlineUsers.push(id);
}
// send the user who just went online to everyone else who is already online
socket.broadcast.emit("add-online-user", id);
});
socket.on("new-message", (data) => {
socket.broadcast.emit("new-message", {
message: data.message,
sender: data.sender,
});
});
socket.on("read-message", (data) => {
socket.broadcast.emit("read-message", data);
});
socket.on("read-messages", (data) => {
socket.broadcast.emit("read-messages", data);
});
socket.on("logout", (id) => {
if (onlineUsers.includes(id)) {
userIndex = onlineUsers.indexOf(id);
onlineUsers.splice(userIndex, 1);
socket.broadcast.emit("remove-offline-user", id);
}
});
});
How can I authenticate user with socket. Feel free to suggest other method aside using passport.
I found the same error in Github and it hasn't been resolved yet.
According to the official document (see "Compatibility with Express middleware" section), you can use express middleware in io.use by using wrap.
const wrap = middleware => (socket, next) => middleware(socket.request, {}, next);
The section shows how to use "express-session" module with socket.io. I guess this way is better for you because you already use it.
I have some issues to initiate passport.
I call the function app.use(passport.initialize()); in the file server.js
In the file auth.controllers.js passport is not detected as initialized
Somebody could explain how to "connect" app.use(passport.initialize()) in the server.js to the file auth.controllers.js ?
here my files :
Server.js
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const helmet = require("helmet");
const morgan = require("morgan");
const networkConfig = require("./config/network.config");
const app = express();
const db = require("./config/models");
db.sequelize.sync();
var corsOptions = {
origin: networkConfig.corsOptions.ORIGIN
};
app.use(helmet());
app.use(cors(corsOptions));
app.use(morgan('combined'));
// parsing sur les requetes en type json
app.use(bodyParser.json());
// parsing des urls encodés
app.use(bodyParser.urlencoded({ extended: true }));
// route de vérification de bon fonctionnement
app.get("/", (req, res) => {
res.json({message: "Bienvenue ici"});
});
require("./routes/user.routes")(app);
require("./routes/oauth2.route")(app);
require("./routes/client.routes")(app);
require("./routes/beer.routes")(app);
const ejs = require('ejs');
const session = require('express-session');
const passport = require('passport');
/*
const beerController = require('./controllers/beer');
const userController = require('./controllers/user');
const authController = require('./controllers/auth');
const oauth2Controller = require('./controllers/oauth2');
const clientController = require('./controllers/client');
*/
// Set view engine to ejs
app.set('view engine', 'ejs');
// Use express session support since OAuth2orize requires it
app.use(session({
secret: 'Super Secret Session Key',
saveUninitialized: true,
resave: true
}));
// Use the passport package in our application
app.use(passport.initialize());
// Start the server
app.listen(3000);
user.routes.js
module.exports = app => {
const users = require("../controllers/user.controllers");
const auths = require("../controllers/auth.controllers")(app);
const router = require("express").Router();
// Create endpoint handlers for /users
router.route('/')
.post(users.create)
.get(auths.isAuthenticated, users.findAll);
app.use('/api/users', router);
};
auth.controllers.js
// Load required packages
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var BearerStrategy = require('passport-http-bearer').Strategy
const db = require("../config/models");
const User = db.user;
const Client = db.client;
const Token = db.token;
const Op = db.Sequelize.Op;
passport.use(new BasicStrategy( (username, password, done) => {
User.findOne({where: { username: username }})
.then(function (data) {
if (!data) {
return done(null, false, { message: 'user does not exist'});
} else {
var verify = data.verifyPassword(password);
if(verify == true) { console.log("verify true"); return done(null, data, {message: 'authentication succeded'})}
}
})
.catch( (err) => {
console.log("Error reason : "+ err);
return done(null, false, { message: 'Something went wrong with you authentication'});
}
)
}
));
passport.use('client-basic', new BasicStrategy(
function(username, password, callback) {
console.log("CLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASICCLIENT-BASIC");
Client.findOne({ id: username }, function (err, client) {
if (err) { return callback(err); }
// No client found with that id or bad password
if (!client || client.secret !== password) { return callback(null, false); }
// Success
return callback(null, client);
});
}
));
exports.isAuthenticated = passport.authenticate('basic', { session : false });
exports.isClientAuthenticated = passport.authenticate('client-basic', { session : false });
How could I resolve this problem ?
Regards,
I'm working doing a login function with node.js Express and are having trouble with sending the session data so my app.js routes know the user is allowed to enter the various sites.
My first thought was to send it when i approve of the login information and redirect to the frontpage in my Auth.js but i can't figure out how to send it so that my frontpage route can see it and handle it with my checkAuth function.
The other idea i had was using a couple of "set/get" routes as shown in my users.js. But can't figure out how i would further implement that.
I don't know which way would be optimal for this sort of application.
This is the Auth.js which is responsible for the login:
const router = require('express').Router();
const User = require("../models/User.js");
const bcrypt = require('bcrypt');
const saltRounds = 12;
router.post('/login', (req, res) => {
// get request from body
const { username, password } = req.body;
//console.log(req.body);
// ask if this is a username with a password
if (username && password) {
// goes through db to see if username exists
User.query().select('username').where('username', username).then(foundUsername => {
try {
if (foundUsername[0].username == username) {
console.log(foundUsername[0].username);
User.query().select("password").where('username', foundUsername[0].username).then(foundPassword => {
console.log(foundPassword[0].password);
bcrypt.compare(password, foundPassword[0].password).then(result => {
console.log(result)
if (result == true) {
// this is where i want to set the req.session.user_id = true;
// and send it to my /frontpage
return res.redirect("/frontpage");
} else {
return res.status(400).send({ response: "wrong username or password" });
};
});
});
} else {
return res.status(400).send({ response: "wrong username or password" });
};
} catch (error) {
return res.status(400).send({ response: "wrong username or password" });
};
});
};
});
module.exports = router;
This is my app.js which checks the incoming request for req.session.user_id
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.static('public'));
app.use(express.json());
// You need to copy the config.template.json file and fill out your own secret
const session = require('express-session');
const config = require('./config/config.json');
app.use(session({
secret: config.sessionSecret,
resave: false,
saveUninitialized: true
}));
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 8 // limit each IP to 8 requests per windowMs
});
app.use('/signup', authLimiter);
app.use('/login', authLimiter);
/* Setup Knex with Objection */
const { Model } = require('objection');
const Knex = require('knex');
const knexfile = require('./knexfile.js');
const knex = Knex(knexfile.development);
Model.knex(knex);
app.get("/", (req, res) => {
return res.sendFile(__dirname + "/public/login.html");
});
function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.send('You are not authorized to view this page');
} else {
next();
}
}
app.get("/frontpage", checkAuth, (req, res) => {
console.log(req.body);
return res.sendFile(__dirname + "/public/frontpage.html");
});
const authRoute = require('./routes/auth.js');
const usersRoute = require('./routes/users.js');
app.use(authRoute);
app.use(usersRoute);
const PORT = 3000;
app.listen(PORT, (error) => {
if (error) {
console.log(error);
}
console.log("Server is running on the port", PORT);
})
});
This is my users.js. This is another way i thought of getting and setting my session value:
router.get('/setsessionvalue', (req, res) => {
req.session.user_id = true;
return res.send({ response: "OK" });
});
router.get('/getsessionvalue', (req, res) => {
return res.send({ response: req.session.user_id });
});
var search = 1 + req.url.indexOf('?'); throws an error saying the statement to my left is undefined. Im using passportjs to create a login/registration page on my angular frontend. trying to make a post request to nodejs results in the above error. Im entirely new to the mean stack and ive tried several different tutorials to get myself up and running but have had some road blocks. can someone point in the right direction?
I've played around with just about every file moving around code and trying different solutions but nothing works, or one problem is solved but another occurs.
server.js
// set up ========================
var DATABASE = "mongodb://localhost:27017/smartHomeDevices";
var express = require("express");
var mongoose = require("mongoose"); //require monogDB Driver
var morgan = require("morgan"); // log requests to the console (express4)
var bodyParser = require("body-parser"); // pull information from HTML POST (express4)
var methodOverride = require("method-override"); // simulate DELETE and PUT (express4)
var passport = require("passport");
//var _ = require("lodash");
var http = require('http');
//setup
//app.models =
require("./Models/moduleIndex");
// Bring in the Passport config after model is defined
require('./config/passport');
//registering routes
var routes = require("./routes");
//Create App
var app = express();
app.use(passport.initialize());
//Add Middleware for REST API
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json);
app.use(bodyParser.json({
type: 'application/vnd.api+json'
}));
app.use(methodOverride("X-HTTP-Method-Override"));
app.use(morgan("dev"));
//CORS Support, makes API Public
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,");
res.header("Access-Control-Allow-Headers", "Content-Type,Authorization");
next();
});
app.use("/", routes);
// Connect to the db
mongoose.connect(DATABASE);
mongoose.connection.once("open", function() {
var serv = http.createServer(function(req, res) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization");
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end();
console.log(routes(req.method, req.url));
}).listen(3000);
//module.exports = app;
console.log("Listening on 3000");
});
routes.js
//setup
var express = require('express');
var router = express.Router();
var jwt = require('express-jwt');
var auth = jwt({
secret: 'MY_SECRET',
userProperty: 'payload'
});
var ctrlProfile = require('./Controllers/ProfileController');
var ctrlAuth = require('./Controllers/RegisterUserController');
// profile
router.get('/profile', auth, ctrlProfile.profileRead);
// authentication
router.post('/register', ctrlAuth.register);
router.post('/login', ctrlAuth.login);
module.exports = router;
/*module.exports = {
"/smartDevices" : require("./Controllers/SmartDeviceController"),
"/registeredUsers": require("./Controllers/RegisterUserController")
};*/
resgisteredUsersControllers.js
//setup
//var Resource = require("resourcejs");
var restful = require("node-restful");
var passport = require('passport');
var mongoose = require('mongoose');
var User = mongoose.model('registeredUserModel');
var sendJSONresponse = function(res, status, content) {
res.status(status);
res.json(content);
};
module.exports.register = function(req,res) {
console.log(req);
console.log("nw logging res");
console.log(res);
var user = new User();
user.name = req.body.name;
user.email = req.body.email;
user.username = req.body.username;
user.setPassword(req.body.password);
user.save(function(err) {
if(err)
console.log(err);
var token;
token = user.generateJwt();
res.status(200);
res.json({
"token" : token
});
});
next();
};
module.exports.login = function(req, res) {
passport.authenticate('local', function(err, user, info) {
var token;
// If Passport throws/catches an error
if (err) {
res.status(404).json(err);
return;
}
// If a user is found
if (user) {
token = user.generateJwt();
res.status(200);
res.json({
"token": token
});
} else {
// If user is not found
res.status(401).json(info);
}
})(req, res);
next();
};
/*module.exports = function(app, route) {
//setup controller for restful
// Resource(app,"",route,app.models.registeredUserModel).rest();
var rest = restful.model("registeredUserModel",
app.models.registeredUserModel
).methods(["get", "put", "post", "delete"]);
rest.register(app, route);
//return Middleware
return function(req, res, next) {
next();
};
};
*/
ProfileController.js
var mongoose = require('mongoose');
var User = mongoose.model('registeredUserModel');
module.exports.profileRead = function(req, res) {
// If no user ID exists in the JWT return a 401
if (!req.payload._id) {
res.status(401).json({
"message" : "UnauthorizedError: private profile"
});
} else {
// Otherwise continue
User
.findById(req.payload._id)
.exec(function(err, user) {
res.status(200).json(user);
});
}
};
Request object does not have url field.
i have the following method to auth my users:
app.all('/*', function(req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// Set custom headers for CORS
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
var auth = require('./auth.js');
router.post('/login', auth.login);
app.all('/api/*', [require('./middlewares/validateRequest')]);
// If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
And my Auth.js
var jwt = require('jwt-simple');
var auth = {
login: function(req, res) {
var username = req.body.username || '';
var password = req.body.password || '';
if (username == '' || password == '') {
res.status(401);
res.json({
"status": 401,
"message": "Invalid credentials"
});
return;
}
// Fire a query to your DB and check if the credentials are valid
var dbUserObj = auth.validate(username, password);
if (!dbUserObj) { // If authentication fails, we send a 401 back
res.status(401);
res.json({
"status": 401,
"message": "Invalid credentials"
});
return;
}
if (dbUserObj) {
// If authentication is success, we will generate a token
// and dispatch it to the client
res.json(genToken(dbUserObj));
}
},
validate: function(username, password) {
// spoofing the DB response for simplicity
var dbUserObj = { // spoofing a userobject from the DB.
name: 'arvind',
role: 'admin',
username: 'arvind#myapp.com'
};
return dbUserObj;
},
validateUser: function(username) {
// spoofing the DB response for simplicity
var dbUserObj = { // spoofing a userobject from the DB.
name: 'arvind',
role: 'admin',
username: 'arvind#myapp.com'
};
return dbUserObj;
}
}
// private method
function genToken(user) {
var expires = expiresIn(7); // 7 days
var token = jwt.encode({
exp: expires
}, require('../config/secret')());
return {
token: token,
expires: expires,
user: user
};
}
function expiresIn(numDays) {
var dateObj = new Date();
return dateObj.setDate(dateObj.getDate() + numDays);
}
module.exports = auth;
This server runs on port 8080.
So when i attempt to go to http://localhost:8080/login i get the following error message:
Error: Not Found
at app.use.bodyParser.urlencoded.extended (/var/www/example/backend/server.js:34:15)
at Layer.handle [as handle_request] (/var/www/example/backend/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/var/www/example/backend/node_modules/express/lib/router/index.js:302:13)
at /var/www/example/backend/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/var/www/example/backend/node_modules/express/lib/router/index.js:321:12)
at next (/var/www/example/backend/node_modules/express/lib/router/index.js:261:10)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:100:14)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
at next (/var/www/example/backend/node_modules/express/lib/router/route.js:104:14)
However it seems that the rest of my auth is working because if i go to:
http://localhost:8080/api/user
I get: {"status":401,"message":"Invalid Token or Key"}
Can anyone tell me why my login does not work?
Full server script:
// BASE SETUP
// =============================================================================
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var es = require('express-sequelize');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
// =============================================================================
//Secure
app.all('/*', function(req, res, next) {
// CORS headers
res.header("Access-Control-Allow-Origin", "*"); // restrict it to the required domain
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// Set custom headers for CORS
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
var auth = require('./auth.js');
router.post('/login', auth.login);
app.all('/api/*', [require('./middlewares/validateRequest')]);
// If no route is matched by now, it must be a 404
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var env = app.get('env') == 'development' ? 'dev' : app.get('env');
var port = process.env.PORT || 8080;
var Sequelize = require('sequelize');
// db config
var env = "dev";
var config = require('./database.json')[env];
var password = config.password ? config.password : null;
// initialize database connection
var sequelize = new Sequelize(
config.database,
config.user,
config.password,
{
logging: console.log,
define: {
timestamps: false
}
}
);
//Init models
var division_model = require('./lb_models/division/division_model')(express,sequelize,router);
var user_model = require('./lb_models/user/user_model')(express,sequelize,router);
var team_model = require('./lb_models/Team')(express,sequelize,router);
app.use('/api', router);
app.use(division_model);
app.use(user_model);
app.use(team_model);
// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);
Try moving your app.use(bodyParser…) statements above the login route. The order of middleware matters. At the time login is called the req object hasn't run through the bodyParser middleware yet.
Also, your router instance is mounted at "/api" so the router methods will never get called for "/login". The following line should be place above your 404 catchall:
app.use('/', router);
Before, you had used app.use('/api', router), which means that your router routes will only be looked at for any request that starts with '/api'. Also, you had place the 'use' statement too far down.
When setting up middleware, the order in which you call app.use() is key. In your server.js, you're setting up your application routes before you set up body parser. Meaning, when the request comes in, is is not parsed before hitting your application logic. You need to move the app.use(bodyParser) parts to the top of your code.
var express = require('express'),
bodyParser = require('body-parser');
var app = express();
var router = express.Router();
var es = require('express-sequelize');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
perphaps you have to move the
app.use("/", (req, res, next) => {
res.status("404").json({message: "Not found"})
})
to the bottom of your code, but before "app.listen()", The order you declare the routes in the router are important, so putting the "app.use" after you declare all theses routes, would search a match with all the previous route and if none is found then it will enter in that last one
Like this:
.
..
...
app.use('/api', router);
app.use(division_model);
app.use(user_model);
app.use(team_model);
app.use("/", (req, res, next) => {
res.status("404").json({message: "Not found"})
})
// START THE SERVER
app.listen(port);
console.log('Magic happens on port ' + port);