DEV Community

Cover image for Getting Started With Popular Express framework
Shubham Singh
Shubham Singh

Posted on

Getting Started With Popular Express framework

Introduction

A huge portion of the Internet’s data travels over HTTP/HTTPS through request-response cycles between clients and servers.
Express is a powerful but flexible Javascript framework for creating web servers and APIs. It can be used for everything from simple static file servers to JSON APIs to full production servers.

  1. Starting A Server Express is a Node module, so in order to use it, we will need to import it into our program file. To create a server, the imported express function must be invoked.
const express = require('express');
const app = express();

const PORT = 4001;
app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

In this example, our app.listen() call will start a server listening on port 4001, and once the server is started it will log 'Server is listening on port 4001'

  1. Writing Your First Route > Once the Express server is listening, it can respond to any and all requests. > For example, if your server receives a GET request at ‘/about’, we will use a route to define the appropriate functionality for that HTTP verb (GET) and path (/about).
// Open a call to `app.get()` below:
app.get('/expressions',(req,res, next)=>{
   // Here we would send back the moods array in response
})
Enter fullscreen mode Exit fullscreen mode

Inside app.js, create a route handler to handle a GET request to '/expressions'. For now, give it a req, res, next callback. For now, log the req object inside the callback. Verify that the route works and logs the request by starting your server and clicking the Refresh Expressions button which will send a GET /expressions request.

  1. Sending A Response
app.get('/expressions', (req, res, next) => {
  res.send(expressions);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)