Building a TypeScript and Node.js App

Building a TypeScript and Node.js App#

Building number-app#

We'll start by setting up the Express server in app.ts:

The html file#

Our server doesn't do much at the moment: we've used express.static() to serve static files in the /dist folder, but that folder is currently empty. Let's create an index.html file so the user at least has a place to land when they land on the home page:

Serving the HTML#

To serve that file, we set up a route for the root page and delivery that file:

Trying it out#

To test that everything is working as expected, we can start our server by running the following command:

Navigating to localhost:3000 will take us to a page containing a heading "Num Info". Once completed, our page will show the following info about a given number:

  • Number of digits

  • Is number even?

  • Is number prime?

Building NumInfo#

We can express that info in a NumInfo type under the file types/NumInfo.ts:

We'll use our new type to create a getNumInfo() function in our app.ts file, but before we can do so let's implement an isPrime() function:

And with that function we can implement getNumInfo() as follows:

Adding a new route#

Now to set up a route that will return the num info when the user hits that route. We'll call this route /numInfo/:num and capture the num in a num parameter which can be captured and used as follows:

Before passing the number to getNumInfo(), we must convert it from a string to a number, so we use the Number() function to do so. To test our new route, start the server again by running npm start and navigate to localhost:3000/numInfo/13 on your browser. You should see the following JSON:

Now that we've completed the backend of our app, we can move on to the client. The idea for the client is that we'll set up a form that allows the user to input a number, and a submit button that will make an API test to our server to get the num info that will then be displayed on the screen.

 

This page is a preview of Beginners Guide to TypeScript

No discussions yet