All Projects → basemkhirat → express-mvc

basemkhirat / express-mvc

Licence: other
A light-weight mvc pattern for express framework with minimum dependencies

Programming Languages

javascript
184084 projects - #8 most used programming language
HTML
75241 projects
CSS
56736 projects

Projects that are alternatives of or similar to express-mvc

MEAN-stack-authentication
MEAN stack authentication boilerplate with Angular 5 and Angular Material
Stars: ✭ 29 (+26.09%)
Mutual labels:  expressjs, mean, mean-stack
mean-stack
MEAN stack Mongoose, Express, Angular6, Node
Stars: ✭ 22 (-4.35%)
Mutual labels:  mongoose, expressjs, mean-stack
mini-express-boilerplate
A minimal Express boilerplate with passport user authentication, mongoose and some security setup configured
Stars: ✭ 15 (-34.78%)
Mutual labels:  mongoose, expressjs, passportjs
passport-examples
A variety of examples using PassportJS with ExpressJS and ReactJS applications
Stars: ✭ 44 (+91.3%)
Mutual labels:  mongoose, expressjs, passportjs
generator-espress
an opinionated yeoman generator that scaffolds a mvc express webapp completely in es6
Stars: ✭ 20 (-13.04%)
Mutual labels:  mvc, mongoose, expressjs
Node Express Mongoose Passport Jwt Rest Api Auth
Node, express, mongoose, passport and JWT REST API authentication example
Stars: ✭ 146 (+534.78%)
Mutual labels:  mongoose, expressjs, passportjs
node-express-mongo-passport-jwt-typescript
A Node.js back end web application with REST API, user JWT authentication and MongoDB data storage using TypeScript
Stars: ✭ 51 (+121.74%)
Mutual labels:  mongoose, expressjs, passportjs
MovieGo
A Website implemented using MERN (MongoDB, ExpressJS, ReactJS and NodeJS) stack, which allows users to sign-in/register and book movie tickets online.
Stars: ✭ 26 (+13.04%)
Mutual labels:  mongoose, expressjs, passportjs
nodeJS examples
Server, routing, db examples using NodeJS v6
Stars: ✭ 34 (+47.83%)
Mutual labels:  mongoose, mean, mean-stack
ng-nest-cnode
Angular 10 Front-End and Nestjs 7 framework Back-End build Fullstack CNode
Stars: ✭ 17 (-26.09%)
Mutual labels:  mongoose, expressjs
WordNook
Dynamically updating blogging website to upload articles and blog posts on various topics, developed using ejs template engine and node js in the backend.
Stars: ✭ 80 (+247.83%)
Mutual labels:  mongoose, expressjs
NodeRestApi
Node.js, Express.js and MongoDB REST API App
Stars: ✭ 38 (+65.22%)
Mutual labels:  mongoose, expressjs
Online-Examination-System
Technologies : React js, Node js, Express js, Mongo Db, Ant Design, Redux js Key features: 1. User management 2. Modular code 3. Permission management 4. Persistent answers on page refresh in the test portal 5. Examination results using graphs 6. Results can directly be downloaded as excel sheet 7. Feedback system
Stars: ✭ 37 (+60.87%)
Mutual labels:  mongoose, expressjs
opentelemetry-ext-js
js extensions for the open-telemetry project
Stars: ✭ 122 (+430.43%)
Mutual labels:  mongoose, expressjs
todo-list
A practical web application built with Node.js, Express, and MySQL for you to readily record, view, and manage your tasks with an account: Create, view, edit, delete, filter, and sort expenses are as easy as pie 🥧
Stars: ✭ 18 (-21.74%)
Mutual labels:  expressjs, passportjs
NodeExpressCRUD
Node, Express, Mongoose and MongoDB CRUD Web Application
Stars: ✭ 45 (+95.65%)
Mutual labels:  mongoose, expressjs
ThinkApp
Test your knowledge with any of the available topic this fun and free Champion Quiz Master App. Save your time and effort by saving your queries & its resolutions
Stars: ✭ 15 (-34.78%)
Mutual labels:  mongoose, expressjs
react-node-twitter-login
Demo application that shows how to enable Twitter login with React on frontend and Node.js/Express on backend
Stars: ✭ 34 (+47.83%)
Mutual labels:  mongoose, passportjs
Backend-NodeJS-Golang-Interview QA
A collection of Node JS and Golang Backend interview questions please feel free to fork and contribute to this repository
Stars: ✭ 122 (+430.43%)
Mutual labels:  mongoose, expressjs
OpenBook-E-Commerce
An e-commerce progressive web application, built with mern stack. It has features like product buy, order management by admin, payment gateway, cart, checkout and lot more.
Stars: ✭ 53 (+130.43%)
Mutual labels:  mongoose, expressjs

Attention

Now, we don't give support for this package as we worked on the core since Jan 2019 to introduce dotapp nodejs framework.

See: DotApp Framework

If you are a maintainer, contact us and you are welcome to have access.

express-mvc

A light-weight mvc pattern for express framework with minimum dependencies

Installation

npm install express-mvc-generate -g

Express MVC generator command will be installed globally so from anywhere you can call it to generate the project skeleton.

express-mvc-generate my-project
cd my-project
npm install
npm start

Server will be created at port 3000 by default. you can change the port later from app configurations.

Browse http://localhost:3000 and have fun.

The config directory

All application configuration files are stored here grouped by its functionalites:

app.js setting the enviromment, port and main app configurations.

db.js setting monogdb connection parameters.

body.js setting the body parser module configurations.

i18n.js setting the current app locale and other localization configurations.

jwt.js setting the secret hash and expiration date used by bycrpt package.

session.js setting all session configurations such as the name and secret hash.

csrf.js setting the Cross-Site Request Forgery protection.

cors.js setting the Cross-Origin Resource Sharing protection.

In production environment. we always need a different configuration parameters that what the config/env directory do.

The application gets the enviroment stored in app.js file and load the evironment file. So if we are working in production environment, the application will automatically load the configuration file config/env/production.js and uses its defined items to override items stored outside.

# production.js

module.exports = {
	db: {
		url: 'mongodb://localhost/production_db_name',
	}
}

We can access configuration using the _config() function. so if we want to get the environment key we call _config('app.env').

Public directory

Here we can put our static files such as image, css, js, uploads and other client side files to be served.

Application directory

Contains the MVC folder structure:

controllers are modules. each of them exports an object of methods that accept request and response.

# HomeController.js

module.exports = {

    /**
     * Show homepage
     * @param req
     * @param res
     */
    index: function (req, res) {
        return res.render("hello world !");
    },
}

routes define app routes definitions.

There are two files. one for web routes (browser routes) and the other for api routes. you can define routes easily.

# web.js

var router = require("express").Router();

router.get("/", HomeController.index);

module.exports = router;

Note api routes defined in api.js are prefixed by default with the value of configuation _config("app.api_prefix");

models define the mongoose collection models that interact directly with database.

# User.js

var mongoose = require("mongoose");

var schema = mongoose.Schema({
        username: {
            type: String,
            unique: true
        }     
});

module.exports = mongoose.model("user", schema, "user");

You should read mongoose docs before writing your models

views define app templates files.

The default engine is ejs. You can change views settings from app.js

# hello.ejs

<h1>
    Hello world <%= _lang("name") %>!
</h1>

middlewares are functions that have access to the request object (req), the response object (res), and the next middleware function in the application’s request-response cycle. The next middleware function is commonly denoted by a variable named next.

# SessionAuth.js

module.exports = function (req, res, next) {

    if (req.isAuthenticated()) return next();

    return res.forbidden();
};

You can call middlwares within routes file using:

router.get("/profile", SessionAuth, HomeController.profile);

services are libraries of functions that you can use from anywhere in your app. For example, you might have an EmailService which tidily wraps up one or more helper functions so you can use them in more than one place within your application. Services are the best and simplest way to build reusable code.

# EmailService.js

module.exports = {

    /**
     * Send emails
     * @param req
     * @param res
     */
    send: function (req, res) {
        // Sending ...
    },
}

From anywhere in your project you can call it EmailService.send()

lang stores the translation keys grouped by each locale.

# en.json

{
	"name": "express"
}

You can get the localized value using the helper function _lang('name')

responses: are custom responses attached to the res object to send a given responses. you can write your own custom response.

# invalid.js

module.exports = function (data) {
	
	var req = this.req; 
	var res = this.res;
	
	// data processing......
	
	return res.send(data);    
});

From controller or middlewares you can call it using res.invalid()

Global helper functions

_config(key) gets the configuration value by key.

_config("app.env");		
// return 'development'

_config("db"); 	
// return { url: 'mongodb://localhost/db_name', options: { useMongoClient: true } }

_lang(key) gets the localized value by key.

_lang("name");		
// return 'express'

_url(path) gets the application base url.

_url();		
// return 'http://localhost:3000'

_url("api/token");		
// return 'http://localhost:3000/api/token'

_url("css/style.css");		
// return 'http://localhost:3000/css/style.css'

Authentication

This application comes with two type of authentication methods:

session for working with server side rendering applications which authentication meta data is stored as session files on server and cookies in browser and browser sends this cookie with any request.

You can set the session using login function

req.login({id: "59f4856fd3b99e1d311ef94a", name: 'john'}, function (error) {
    if (error) return next(error);
    return res.redirect("/profile");
});

Also you can use the builtin SesionAuth middleware to protect your routes.

router.get("/profile", SessionAuth, HomeController.profile);

To logout please use the logout function

req.logout();

jwt authentication suitable for building APIs.

In this type we only generate a json web token for the user payload object using the sign function

jwt.sign(
    user.toJSON(),
    _config("jwt.secret"),
    {expiresIn: _config("jwt.expires")}
);

// return '.eyJ1cGRhdGVkQXQiOiIyMDE3LTEwLTMwVDE3OjQxOjQzLjExOFoiLCJjcmVhdGVkQXQiOiIyMDE3LTEwLTMwVDE3OjQxOjQzLjExOFoiLCJlbWFpbCI6ImF0ZWZAZ21haWwuY29tIiwicGFzc3dvcmQiOiIkMmEkMTAkUlJZb3Z5YlFZSGx0NFRZOWNXSzhZLjd0QlozN1ZNU0p1SXZkYmNZSGVoVFRwcjlOczFEMUMiLCJmaXJzdF9uYW1lIjoic2RmIiwiX2lkIjoiNTlmNzY0NTdjNzU2MmM1ODkxYjkzNmYxIiwidXBkYXRlZF9hdCI6IjIwMTctMTAtMzBUMTc6NDE6NDMuMTE4WiIsImNyZWF0ZWRfYXQiOiIyMDE3LTEwLTMwVDE3OjQxOjQzLjExOFoiLCJsYW5nIjoiZW4iLCJzY29yZSI6MCwiaWF0IjoxNTA5Mzg1MzAzLCJleHAiOjE2MDkzODUzMDJ9.JCYlwK66EbHXsGeZw12MXC5RhUbiJIG_G3xV-2Qyvws'

This token will be sent to the client (browser or mobile) and the client will store and send it every request using the query string parameter ?token=thehashhere

You can use the built-in TokenAuth middleware to protect your routes

router.get("/user", TokenAuth, UserController.find);

You can check if user is logged in using:

req.isAuthenticated();		// return true or false

You can get the current user

req.user;		// return a json of user object

Redirection

The response method res.back() is added with express to redirect to the previous page.

Author

Basem Khirat - [email protected] - @basemkhirat

Bugs, Suggestions and Contributions

Thanks to everyone who has contributed to this project!

Please use Github for reporting bugs, and making comments or suggestions.

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].