Express Js tutorial – Hello world example

The Express js, is a framework that sits on top of Node.js’s web server. Express js is easier to use and a very popular Nodejs framework, Express has many features but Middleware and routing, are two popular features of Express.

What is Express js?

Express.js is one of the most popular frameworks that build on Node.js. Express web framework is based on core Node.js http module and Connect components. Express js allows us to create our own web server and build web applications on top of it. We don’t need to run separate web servers like Apache, NGINX, or ISS. Thus we have greater control of how our web server works and developers have greater responsibility.

Node js gained its popularity back in 2009, Node is a Javascript runtime built on Google Chrome V8 Javascript engine. With Nodejs developers can run server-side code written in Javascript. Node.js encourages an asynchronous coding style, making for faster code while avoiding multithreaded nightmares.

Nodejs is non blocking. Express builds on top of its features to provide easy-to-use functionality that satisfies the needs of the Web Server use case.


Express js example

Let’s first create a simple example of an express server to display Hello world by accessing the root page. Here is the screenshot of our first example.

express js example

How to set up express hello world?

We have seen the above screenshot of the express hello world example. Here is the step to creating an express hello world.

Step 1: Create a project folder: We need to install Node.js, create a directory to hold your application, and make that your working directory.

$ mkdir myapp
$ cd myapp 

Step 2: Create a package.json file: Once we have our working directory, Use the npm init command to create a package.json file for our application.

$ npm init

Running the above command prompts you for a number of things, such as the name of the project, version, description, entry point, and more options about our project.

express hello world

Most prompt information is optional, and at last, we need to press yes.

Step 3: Install the express package: We need to install the express package to create our express server.

npm install express --save

Step 4: Create our basic Hello world example: We need to create a file to create a server, let’s say server.js

const express = require("express");
const app = express();

app.get("/", function(request, response) {
   response.send("Hello, world!");
});

app.listen(3000, function() {
   console.log("Express app started on port 3000.");
});

We can use the express listen function to create our express server. The express() function is a top-level function exported by the express module.


Express js minimal philosophy

Express is a framework, the developer doesn’t have to follow some rigid structure or standard. Express is flexible and allows developers to choose a wide variety of other libraries in express applications. It is the developer responsible for knowing what and which libraries to use in our express application.

The core parts of Express js

The Express has just four major features: middleware, routing, sub-applications, and conveniences.

  1. Middleware
  2. Routing

Middleware

Node.js gives you one request handler function to work with. When a request comes into your function and the response goes out of that function.

In express rather than one monolithic request handler function, we can call several request handler functions that each deal with a small chunk of the work. These smaller request handler functions are called middleware functions, or middleware.

We can have authentication middleware, error handling middleware, serving static files in our express application and many more we can do with middleware. All requests to the Express server run through the middleware.

Routing

Routing is the process of navigating to different resources based on URL and HTTP method requests from clients. We can execute different request handlers based on client requests of HTTP method and URL.

Note: The JavaScript function that processes browser requests in your application is called a request handler. Request handler functions take two arguments: the request and the response.

The routing request handler or callback function is called a controller. Express controllers manage the application logic. In a default Express setup, controllers are part of the routes, but we can separate them out in the different files.


Create express with next

Let us create the app.js file that will have our express apps in this file.

const express = require('express');

const app = express();

app.use((req, res, next) => {
   console.log('First call here - middleware first');
   next();
};

app.use((req, res, next) => {
   res.send('Hello world');
   next();
};

module.exports = app;

The use function here in its simplest form takes a function that is executed for an incoming request and the function takes three arguments.

  1. request
  2. response
  3. next

The next function has one important purpose if we execute it like the next(). It will actually continue its journey.


Express Js with details like connecting mongoose Db

We need to specify and configure the database for real applications. We need to install mongoose packages.

npm i mongoose

Create a file called database.js in the root folder and add the following code.

const mongoose = require('mongoose');

function DbConnect() {
    const DB_URL = process.env.DB_URL;
    
    mongoose.connect(DB_URL, {
   // Database connection
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });

    const db = mongoose.connection;
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', () => {
        console.log('DB connected...');
    });
}

module.exports = DbConnect;

We need to add our DB_URL, let’s add this .env file in the root folder.


....
DB_URL=mongodb://....some..url
JWT_ACCESS_TOKEN_SECRET= ....somehashkey...
JWT_REFRESH_TOKEN_SECRET=  ....somehashkey...
BASE_URL=http://localhost3000

Now let’s add the following code in our server.js file, here we need to create a server and register all middle, DB routing, and more.

const express = require("express");
const app = express();
const server = require('http').createServer(app);
const DbConnect = require('./database');

// Create PORT
const PORT = process.env.PORT || 3000;

// For multipart data - inbuilt middleware
app.use(express.urlencoded({ extended: false }));

// For  parses incoming requests with JSON payloads and is based on body-parser
app.use(express.json({ limit: '10mb' }));

// For Db connection
DbConnect();

// app.use(router); Create routing in routes.js

// Enable CORS - Cross-Origin Resource Sharing
app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, DELETE, OPTIONS"
  );
  next();
});

app.use("/storage", express.static("storage"));

// To access localhost:3000 in browser
app.get("/", (request, response) => {
  response.send("Hello, world!");
});

// To access localhost:3000/hotels in browser
app.use('/hotels', (req, res, next) => {
   return res.status(200).json({
      message: 'Hotel data fetched successfully',
      posts: [
         {id:1, name: 'Taj Delhi', location: 'Delhi'},
         {id:1, name: 'Hilton', location: 'New York'},
         {id:1, name: 'Hyatt', location: 'Mumbia'},
      ]
   });
});

server.listen(PORT, () => console.log(`Listening on port ${PORT}`));

The Http is not the package we need to install and is the default node package that was already with Nodejs on your system. We can use the http package to create a new server as HTTP packages have created a server method here.

Body-parser is the Node. js body parsing middleware. It is responsible for parsing the incoming request bodies in middleware before you handle them.

To attach middleware that works like here but which is only triggered for an incoming post request, respectively, we have app.get(), app.put(), and app.delete().

Install nodemon package : The nodemon is a tool that helps develop node.js based applications by automatically restarting the node application when file changes in the directory are detected.

npm install --save-dev nodemon

To run nodemon we can add a script in packages.json

'dev': 'nodemon server.js' // For development
'start': 'node server.js' // For production

To run nodemon in terminal 
$npm run dev

So if we want to access localhost:3000/api/posts to get hotels details, it will only request-target of localhost:3000/api/posts.


The Express CORS errors

app.post('/api/posts', (req, res, next) => {
  const post = req.body;
  console.log(post);
  res.status(201).json({
    message: 'Post added successfully'
  });
});

The CORS stands for cross-origin resource sharing, as our server and client are at different locations. For security reseason, we should not able to access the data on a server, from another location, or from a host other than the server. So if the request is coming from a different address, this will give us a CORS error.

Express cors allow all

To make server API access to all possible clients, so we have to disable this default mechanism. This can be fixed by setting the rights header on the server-side response using middleware. There are two ways to fix express cors.

  1. CORS package: use of third-party package cors.
  2. Adding our own custom code to enable Express CORS to enable API access to all possible clients.

Approach 1: Use of the CORS package

Use of cors packages, CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options. But this package has been updated for the last three years.

npm i cors

In our server.js let’s import cors packages and use them as middleware.

....
const cors = require('cors');

.....

app.use(cors());

Approach 2: Custom code to set header

We can add the following custom code to set the header to enable Express cors, to allow access to all possible clients. Add this code before any response to the client.

app.use((req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  res.setHeader(
    "Access-Control-Allow-Methods",
    "GET, POST, PATCH, DELETE, OPTIONS"
  );
  next();
});

Where * is indicated from any domain or host the client can be sent a request to our server.

Related Post

  1. https://edupala.com/how-to-implement-express-routing-with-example/

Spread the love

Leave a Comment

Your email address will not be published.

Scroll to Top