Why Express.JS with Typescript

2 minute read

I love Typescript the way it helps development speed and accuracy. I wanted to work with Typescript, Webpack and Express.JS finally came up with a project where we can use webpack, typescript, karma, jasmien and express.js. All together and do nice development. Please read this article to get more details.

Why ExpressJS?

ExpressJS is a web framework for node.js server. It is backend component for node.js environment. I helps to host your server side capability in HTTP web Apis. ExpressJS is used in MEAN stack where M is for Mongo Db, E is for ExpressJs , A is for Angular and N is for Node.js

https://www.youtube.com/watch?v=9a1KL9wrREg&t=2s

How to Use ExpressJS?

Create app by calling express next you can configure routes and start listening at some port number.

import * as express from 'express';
const app = express();
const PORT = 3432;
app
.get('/', (req,res)=>res.send(`your server is running`))
.listen(PORT, ()=> console.log(`your server is running at port ${PORT});

// now you can navigate to http://localhost:3432/ 

Example of ExpressJS with Typescript

Good example is to see the live sample app. Here is the live sample project https://github.com/roopkt/Training-Typescript-ExpressJS-Sample-App This project is runing with typescript and webpack. In this app we have client and server projects. Server project has expressjs in it.

Here are few snippets for scripts that we can add for runing expressjs.

 "build:server": "tsc --project server/tsconfig.json -w",
 "watch:server": "nodemon -w dist/server --exec \"node dist/server/index.js\"",
 "start:server": "concurrently npm:build:server npm:watch:server"

https://github.com/roopkt/Training-Typescript-ExpressJS-Sample-App

What is middleware why we need it example of midleware?

In express.JS Middleware is a function that has access to both request and response object. It can perform some operation before even returning response to client. In Express.JS middleware function we get 3 parameters request, response and nextnext is function that must be called becuase it enables the Express.JS to call next middleware or next function in the HTTP pipeline.

Here is one example of middleware where we want to add access-allow-origin in header

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  // allow access for Delete and other verbs
  response.header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE");
  next();
});

What is body parser why we need it?

Body Parser is usefull to read the body data from the HTTP message and put it into the epressjs Request object. In order for installing body parser in your project you need to run below script

npm i -S body-parser

Once it is installed please add this into expressjs app. Body Parser will work like a middleware and it will intercept each http request.

// body parser will help to read the body from request message and put it in express request body object.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

How to allow Cross Origin Access in ExpressJS API's?

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );
  next();
});

Why jQuery POST is not working with ExpressJS?

You need to add body parser install by running npm i body-parser

import * as express from 'express';
var bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

Example of jQuery POST that works with ExpressJS

const product = { id : 23, name : 'orange' };
$.post('http://localhost:3244/api/products', product).done(onSuccess).fail(onFail);

Example of jQuery Delete and ExpressJS

 $.ajax({
  url:`http://localhost:3244/api/products/23`,
  type:`DELETE`
 }).done(onSuccess).fail(onFail);

In your ExpressJS route you will have below code

app.route('/api/products/:productId`,(req,res)=>{
 const productId = req.params.productId;
 // delete product from db.
 res.send(`product deleted successfully ${productId}`);
 
});