Introducing Express support into our application

When we develop client/server applications with Node.js, it makes our lives a lot easier if we can use a framework that allows us to develop the server-side part, especially if it comes with a rich ecosystem of add-in functionality to cover features such as connecting to databases and working with the local filesystem. This is where Express comes into play; it's a middleware framework that fits neatly alongside Node.js.

As we are going to create our server-side code completely from scratch, we should start off by creating the base tsconfig.json and package.json files. To do this, run the following commands in the Server folder, which will also add Express support by importing the Express and TypeScript Express definitions:

tsc --init
npm init -y
npm install express @types/express parser @types/body-parser --save

There are a number of unnecessary options in our tsconfig.json file. We only need the bare minimum of options, so we set our configuration to look like this:

{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
},
}

Our server-side code is going to start with a class called Server. This class is going to import express:

import express from "express";

In order to create an instance of the Express application, we are going to create a private instance called app and set it to express() in the constructor. This has the effect of initializing the Express framework for us.

The constructor also accepts a port number, which we will use when we tell our application to listen in our Start method. Obviously, we need to respond to web requests, so when our app receives a get request from /, we are going to respond by using send to send a message back to the web page. In our example, if we navigate to http://localhost:3000/, the web page URL that this method receives is the root and the function that is called returns Hello from the server back to the client. If we browse to anything other than /, our server will respond with 404:

export class Server {
constructor(private port : number = 3000, private app : any = express()) {
}

public Start() : void {
this.OnStart();
this.app.listen(this.port, () => console.log(`Express server running on port ${this.port}`));
}

protected OnStart() : void {
this.app.get(`/`, (request : any, response : any) => res.send(`Hello from the server`));
}
}

To start our server, we must give it the port that we want to serve the content from and call Start:

new Server(3000).Start();
The reason that we have started off with a Server class, rather than following the approach of most Node.js/Express tutorials we see on the internet, is that we are looking to build the foundations of something that we will be able to re-use in future chapters. This chapter represents a starting point for this class, as future chapters will take what we have done here and grow the capabilities of the server.

In its current state, the server will not be able to handle any incoming requests from Angular. It's time to start enhancing the server so that it can cope with requests that come across from the client. When the client sends its data, it will come across as a JSON-formatted request. This means that we need to tell the server to take the request and expose it in the body of any request we see.

When we cover routing, shortly, we will see an example of us taking in the request.Body in its entirety. Something that we have to be aware of is that we will receive large requests from Angular; photographs can take up a lot of space. By default, the body parser has a limit of 100 KB, which won't be large enough. We are going to raise the limit for the size of requests to 100 MB, which should be more than enough for any image we care to throw at our picture gallery:

public Start(): void {
this.app.use(bodyParser.json({ limit: `100mb` }));
this.app.use(bodyParser.urlencoded({ limit: `100mb`, extended: true }));
this.OnStart();
this.app.listen(this.port, () => console.log(`Express server running on port ${this.port}`));
}

Now that we are talking about the data that is going to come across from Angular, we need to think about whether or not our application will accept the requests. Before we get into the topic of how our server will know which operation to perform based on which request, we need to address the issue of something called Cross-Origin Request Sharing (CORS).

With CORS, we let known outside locations have access to restricted operations on our site. As Angular is running from a different site to our web server (localhost:4200 as opposed to localhost:3000), we need to enable CORS support to post; otherwise, we will not return anything when we make requests from Angular. The first thing we have to do is add the cors middleware to our Node.js server:

npm install cors @types/cors --save

Adding CORS support is as simple as telling the application to use CORS:

public WithCorsSupport(): Server {
this.app.use(cors());
return this;
}
CORS support provides a lot of fine-tuning that we don't need to take advantage of. For instance, it allows us to set the types of request methods that we are allowing, using Access-Control-Allow-Methods.

Now that we can accept requests from Angular, we need to put the mechanism in place to route requests to appropriate request handlers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.6.194