
Setting up a basic server with express.js
3.1 Introduction
Express.js is a node.js framework and much of express.js is writing logic to handle GET/POST requests at different URI paths in your web app/site.
As we’ve read up to now that data travels through HTTP request-response cycle from the browser to the server and back. Express.js allows you to create a web server and routes for handling client/browser requests.
3.2 Setting up
1. Create a dir and lets call it express_tut
2. Navigate to the dir ‘express_tut’
3. Install npm (which will create a package.json file) and then install express as a dependency :
npm init –yes
npm install –save express
4. Inside your dir/folder create a server.js file which is empty right now.
After you’re done the express_tut folder will have:
– node_modules subfolder
– server.js file
– package.json
3.3 Basics
1. Creating a server:
const express = require(‘express’);
const app = express();
const Port = 3000;
The ‘require’ method imports the express node module. And then we return an object instance of express and assign it to const app, which then you can use to start a server.
const Port refers to the port number that the server will be listening for requests on
2. Listening for requests:
app.get(‘/’, (request, response) => {
response.send(‘hello world!’);
});
app.listen(Port, () => {
console.log(‘Express intro running on localhost:3000’);
});
The server, as declared by const app, listens for requests via the ‘listen method’ which takes const Port as the 1st argument and an anonymous function as the 2nd argument which will console log the string ‘Express intro running on localhost:3000’.
app.get( ) will create a route handler . Route handlers will handle how client’s requests will be handled and routed.
A server listens for requests, in order to do something with the requests it must “ROUTE” the request somewhere. Routes define the control flow for requests based on the requests “PATH” and “HTTP Verb”. The path refers to the path on server, and in our case the root of the directory which is “/”. The HTTP verb refers to “GET, POST, PUT & DELETE” verbs.
app.get( ) will take 2 arguments:
- Path
- Callback function
The callback function takes the request and response objects as arguments. The request object will contain information about the ‘Request Message’ that came from the browser (Request header and body). The Response object will contain information that the server will send back to the browser. Which in out case is the string ‘hello world!’.
4. Get back to your terminal
In your terminal type in:
node.js server
So if you go to the terminal you should see the string ‘Express intro running on localhost:3000’.
5. Browser
In your browser address bar type in:
localhost: 3000
You should see the string hello world!