Express 4 was released a while ago and although the API is pretty much the same as version 3, there are some breaking changes which I recommend you to take a look at this page in case you want to move your express 3 application to express 4.
Version 4 changed to Express core and middleware system. Which means the dependency on Connect framework which was built-in Express is removed and you must separately download and add the middleware you want to your application. Also the routing system has changed and the new router has much more flexibility.
I’m planing to write a tutorial series on Express 4. In this tutorial we’re writing a very basic Express 4 app and connect it to a (dummy)Database and authenticate users.
Source Code
Applicaiton Structure
App
- public -> We put static files here
- views -> Our Jade template views are here
- routes -> Different routers of the application stay here
App.js
If you are familiar with Express 3, this is code also looks familiar to you. The difference is that now we have to load cookie-parser
, body-parser
and express-session
and load them into our applicaiton as a middleware by app.use()
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
|
Routers
Each route file in routes folder exports a router which takes routes for a specific part of the application and like middlewares we load them into the applicaiton by app.use()
1 2 3 4 5 6 7 8 9 10 |
|
Source code
This simple app, sign you up as a user and saves in session. You can access your profile and other users profile by going to localhost:3000/user/:id
which you have to put a valid user id, otherwise you receive 404. This simple app also restricts you to access users’ profile if you’re not logged in and restricts your access to pages such as login and sign up after you are signed in.
You can find the code HERE
To run the application install the dependencies npm install
and then npm start