Tute 02: Nodejs and expressjs - ariffira/node-basic GitHub Wiki
ExpressJs:
- Backend nodejs framework provides API
- no best way, so extendable and minimal interface
We will learn here how to use expressJs Framework which is very basic but important.
Our goal of this tutorial is:
- express setup
- express route system
Express setup:
Open a directory of your choice. For me I have directory called node-basic already from my previous tutorial. Go inside the directory from CMD or terminal or git bash.
npm init
// it will create a package.json file for you.
Do as below like i did:
package name: (basic) node-basic-app //give your app name
version: (1.0.0) //keep empty
description: nodejs mongodb express basic app //give some description of the app
entry point: (helloNode.js) app.js //app or index is better
test command: //keep empty
git repository: (https://github.com/ariffira/node-basic.git)
keywords: //keep empty
author: MD Ariful Islam //give your name
license: (ISC) //keep empty
After that it will show you package.json file and ask you to confirm by 'yes'.
Is this ok? (yes) yes
//write yes and enter
Please open package.json file. Now we will talk little bit about our package.json which will keep all dependencies and basic information and also scripts for us. First add some dependencies like below after scripts.
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"dependencies": {
"express": "*"
},
Change this line "start": "node server.js"
as node app.js
because we want to use app.js as initial file and server. Now intall expressJs by this command:
npm install
// it will create node_modules folder and keep all necessary js library like express and dependencies there
Now go to node-basic directory and you see you have node_modules directory and inside there you have many files include express also. nice :)
So far we do not have app.js yet. create one file inside node-basic directory as app.js and include below code:
// include expressjs
const express = require('express');
// use express function to app variable. express() is a top-level function exported by the express module
const app = express();
// create a get routes for '/' with arrow function
app.get('/', (req, res) => res.send('Welcome to ExpressJS!'));
// another route without arrow function
app.get('/test', function(req, res){
res.send("My Test route!");
});
app.listen(3000);
Run your code now using: npm start or node app
So, go to your browser as: localhost:3000 and localhost:3000/test
You see two different routes. Now write something else in this route as localhost:3000/hello and you will see can not GET /hello because you do not have it. Now compare this app.js with server.js and you will see that you do not need http createServer() etc. why ??? because express will do this stuff for you.
Now update this line from app.js as:
app.listen(3000, () => console.log('My App listening on port 3000! Express is awesome!!!'));
Now run npm start again and you will see some console messages in your console.
We have some boring problem here :( change the code and re-run. Well, we can do some smart stuff using nodemon. Install it and it will restart every time you change something.
npm install --save nodemon
//locally only for this app
npm install -g nodemon
globally for all node js app
Then add this line "app": "nodemon app.js"
to package.json
Instead of npm start do this npm run app
That will run nodemon and app.js for you and anything you will change nodemon will restart server. Cool right?
Lets know more about Routing
- how an application’s endpoints (URIs) respond to client requests
- create API endpoints for us
- methods are: get(), post(), delete(), put() and all() etc.
Now create some routes in our app.js file as below:
// home page route by get method
app.get('/home', function (req, res) {
res.send("<h1>Homepage</h1>");
});
// login page route by post method
app.post('/login', function (req, res) {
res.send("<h1>Login Page</h1>");
});
// login page route by post method
app.all('/gallery', function (req, res) {
res.send("<h1>My Gallery</h1>");
});
Check this routes and you see localhost:3000/login does not work because it is a post request and it is suppose to post some data and return back.
You can still test it by curl -X POST "http://localhost:3000/login"
from your terminal and see result in console.
get() and all() works fine.
How about using ID for users as if we want to get some users data from ID. It should be similar to that:
// user page route by post method
app.get('/user/:userId', function (req, res) {
res.send("<h1>User Profile Page by User Id: " + req.params.userId + "</h1>");
});
Here req.params will have parameters from the http request as
Route path: /user/:userId
Request URL: http://localhost:3000/user/1
req.params: {"userId": "1"}
You can send any types parameter or data this way.
Express.Router:
- modular and maintainable routes
- separate routes from app.js or server
Lets create a file inside a routes directory as: routes/myRoutes.js
var express = require('express');
var router = express.Router();
// Contact routes
router.get('/contact', function(req, res){
res.send("<h1>Contact Us</h1>");
});
// dashboard routes
router.get('/dashboard', function (req, res) {
res.send("<h1>Dashboard Page</h1>");
});
module.exports = router;
Then add const myRoutes = require('./routes/myRoutes.js');
as import module of routes in app.js file.
Add below code also before app.listen():
// use myRoutes to get all routes from there
app.use('/myRoutes', myRoutes);
Now if you see we have imported myRoutes and all its routes inside this app.js and use it as /myRoutes
If we browse now as localhost:3000/contact it will not work because this route will start from localhost:3000/myRoutes that means we need to browse this as localhost:3000/myRoutes/contact
This is very smarter way to handle routes in separate file and also easy to maintain and control this way.