Intro to Express

What is Express and the Node Web Server Ecosystem

When it comes to creating a Web Server no framework in the Node ecosystem stands as tall as ExpressJS. It’s a minimalistic unopinionated framework that gives you a lot of flexibility as far as customization. If you enjoy minimalistic frameworks ExpressJS isn’t the only option that Node has to offer…

  • Fastify
  • Polka
  • Merver (My Own Creation)
  • FoalTS
  • Sails
  • Loopback
  • SocketIO (For Real-Time Applications like chat)

Getting Started With Express

It is assumed you have installed Node and NPM, which you can do at nodeJS.org

  • Nodemon: Command to run our files and watch our project files so it will re-run our server when there are file changes.
/node_modules
.env
//BRING IN EXPRESS
const express = require("express")
//CREATE EXPRESS APPLICATION OBJECT
const app = express()
//PORT THE SERVER WILL LISTEN ON
const PORT = process.env.PORT || 3000 //use environment variables and if not, 3000
//OUR SEVER LISTENER, SHOULD ALWAYS BE AT THE BOTTOM
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`)
})
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
//BRING IN EXPRESS
const express = require("express")
//CREATE EXPRESS APPLICATION OBJECT
const app = express()
//PORT THE SERVER WILL LISTEN ON
const PORT = process.env.PORT || 3000 //use environment variables and if not, 3000
//ROUTES DEFINED BY A FUNCTION NAMED AFTER THE VERB ITS RESPONDING TO
//Takes a string for the endpoint, and a callback to define handling
app.get("/",(request, response) => {
response.send("Hello World") //Sending back a text response
})
//THIS ROUTE HAS A URL PARAM, VARIABLE IS NOTED WITH A COLON
app.get("cheese/:param", (request, response) =>{
const {params, query} = request //Destructuring URL params and URL queries from request object
response.json({params, query}) // Sending a JSON Response
})
//OUR SEVER LISTENER, SHOULD ALWAYS BE AT THE BOTTOM
app.listen(PORT, () => {
console.log(`Listening on port ${PORT}`)
})

Other things you can do

Read the express documentation to learn how to do the following:

  • Render templates using response.render in the templating language of your choice (ejs, pug, handlebars, mustache, express-react-views)
  • use middleware to parse request bodies (express.json() & express.urlencoded())
  • create clusters of routes with routers (express.Router())

Templates

Here are some templates you can scaffold for express…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Alex Merced Coder

Alex Merced Coder

59 Followers

Alex Merced is a Developer Advocate for Dremio and host of the Web Dev 101 and Datanation Podcasts.