Telerik blogs

In this post, we’ll go over a few things to consider while developing an Express server. 

In this post, we will demonstrate how to create a basic Express server and perform simple HTTP requests for resources present on our server, and we’ll go over some of the things to keep in mind when doing so.

Project Setup

First, we need to have Node.js installed on our device because Express is a JavaScript framework for creating servers with Node.js. You can get the latest version of Node.js here. Now, let’s go ahead and set up our Node.js application.

npm init --yes

This command will initialize our Node.js application and create a package.json file in our project directory.

{
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Update the content of the scripts in your package.json file to look like so:

"scripts": {
  "start": "node index.js"
},

Create a file in the root directory of your project and name it index.js. This will serve as the entry file for our application. Next, let’s install Express. Run the following command in your terminal:

npm install express

Add the following to your index.js file:

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

app.get('/', (req, res) => {
  res.send('Hello World');
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

Type the command below in your terminal to start up your server:

node index.js

Now, if we navigate to localhost:5000, we get the response "Hello World".

We’ve set up our app to receive requests, but for communication to be possible between our application and any other that wants to connect to it, we need to integrate some extra features.

CORS

CORS, which stands for cross-origin resource sharing, is a security mechanism implemented by servers. It enables a server to specify a list of domains or ports that have access to resources in its domain. With CORS specified, external requests for resources made to our server will not be permitted to access those resources. CORS is usually sent alongside HTTP headers.

Browsers requesting resources first send a “preflight” request to the server where the cross-origin resource is present to verify if the server will approve the request for a resource. Other request-related information, such as HTTP method and headers, is sent during preflight.

Now, let’s implement CORS in our application. Run this command in your terminal to install the CORS package:

npm install cors

Let’s update our index.js file with the following code with CORS installed and enabled.

const express = require('express');
var cors = require('cors');
const app = express();
var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.get('/', (req, res) => {
  res.send('Hello World');
});
app.get('/cors-enabled', cors(corsOptions), (req, res, next) => {
  res.send('This link is cors enabled');
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

In the code above, we require cors, and then we set some option configurations we want our cors to operate by, which specifies that our code should only permit requests for a resource from http//:example.com. This is then assigned as a middleware to be functional for only a single route, i.e., a get request to the cors-enabled route.

Middleware

In the code above, we saw an example of middleware (cors). A middleware function is a function that sits between a request to a resource and the response to be sent back. It has access to the request object, responses object and the next() function in the application’s request-response cycle. It can process the request before the server sends a response.

A middleware function can be joined to other middleware functions resulting in a chain executed in order. A middleware function can invoke the next middleware function by calling next() or end the request by sending a response to the client.

From the cors example above, we have:

app.get('/cors-enabled', cors(corsOptions), (req, res, next) => {
   res.send('This link is cors enabled');
})

The position of cors(corsOptions) is where middleware is specified. Middleware functions play a vital role in processing requests received from HTTP requests and performing checks, security features, authorization functions, etc.

There are two ways of implementing middleware functions in Express. You can specify middleware to take form and capture the HTTP request to process a specific route or specify it for all routes.

Settings for a Single Route

The middleware is appended to the route that handles that particular request, and it sits between the URL path the route intends to capture and the final controller function we write to fetch resources and send responses back.

app.get('/cors-enabled', cors(corsOptions), (req, res, next) => {
   res.send('This link is cors enabled');
})

Settings for All Routes

The middleware is appended to the Express app and implemented by the call to app.use() with the middleware function specified, and this is done before any route is handled.

app.use(express.json());

Body-Parser

Body-parser is a Node.js body parsing middleware that validates the request body sent from the client before it is sent to the server. Body-parser parses Raw data, JSON, text and URL Encoded Request body using four types of middleware. The four major HTTP methods used during resource requests are Get, Post, Put and Delete. Post and Put requests are majorly parsed because they need to send data to the server.

Before the release of Express 4.16, you need to install the body-parser package to use it; however, starting with Express 4.16+, it has been included in the default Express package and no longer has to be installed separately.

const express = require('express');
const app = express();
app.get('/', (req, res) => {
  res.send('Data fetching request');
});
// using the express parser on json data
app.use(express.json());
app.post('/books', (req, res) => {
  res.send(req.body);
});
//express requests for raw data parsing
const ymlParser = express.raw({ type: 'application/yml' });
app.post('/author-name', ymlParser, (req, res) => {
  console.log(req.body);
  res.send(req.body);
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Listening on port ${port}...`));

Conclusion

In this post, we went over a few things to consider while developing an Express server. That’s it for now; Please let me know if you have any questions or suggestions.


Ifeoma-Imoh
About the Author

Ifeoma Imoh

Ifeoma Imoh is a software developer and technical writer who is in love with all things JavaScript. Find her on Twitter or YouTube.

Related Posts

Comments

Comments are disabled in preview mode.