DEV Community

Cover image for Express.js for Beginners: GET, POST & Serving Static Files
renam singla
renam singla

Posted on • Edited on

Express.js for Beginners: GET, POST & Serving Static Files

When building web apps with Node.js, handling requests and sending responses manually can get messy. That’s where Express.js comes in — a lightweight framework that makes it simple to define routes, handle GET and POST requests, and even serve static files like HTML, CSS, and JavaScript.

Express is a node.js web framework(un-opinionated).

It is required:-

  • Write handlers for requests with different HTTP verbs at different URL paths (routes).
  • For setting up servers for web applications
  • To use middleware for tasks like parsing request bodies
  • Serving static files efficiently

In a traditional data-driven website, a web application waits for HTTP requests from the web browser (or other client). When a request is received the application works out what action is needed based on the URL pattern and possibly associated information contained in POST data or GET data. Depending on what is required it may then read or write information from a database or perform other tasks required to satisfy the request. The application will then return a response to the web browser, often dynamically creating an HTML page for the browser to display by inserting the retrieved data into placeholders in an HTML template.

CREATING A SERVER-

in the terminal of the right directory

npm init --y
npm i express

//install nodemon(just once)
npm install -g nodemon

//create a js file- app.js in the same directory
//to start the server

nodemon app.js
Enter fullscreen mode Exit fullscreen mode

After installing, in order to create a server in our app.js file, we require(import) express module and create an express application.

This app starts a server and listen to the port- 4444 for connection.

const express= require('express');
const app= express();
const PORT= 4444;

app.get('/',(req,res)=>{
        res.send("hello world");
})

app.listen(PORT,()=>{
     console.log(`http://localhost:`+PORT);
})
Enter fullscreen mode Exit fullscreen mode

ROUTE handlers-

Routing refers to how an application’s endpoints (URIs) respond to client requests. For an introduction to routing, see Basic routing.

You define routing using methods of the Express app object that correspond to HTTP methods; for example, app.get() to handle GET requests and app.post to handle POST requests. For a full list, see app.METHOD. You can also use app.all() to handle all HTTP methods and app.use() to specify middleware as the callback function

app.METHOD(PATH, HANDLER)
Enter fullscreen mode Exit fullscreen mode

Where:

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase.
  • PATH is a path on the server.
  • HANDLER is the function executed when the route is matched.

GET REQUEST (res.send, req.query, req.params)-

IT IS USED TO READ DATA

The middle part of the code (the three lines starting with app.get) shows a route definition. The app.get() method specifies a callback function that will be invoked whenever there is an HTTP GET request with a path ('/') relative to the site root. The callback function takes a request and a response object as arguments, and calls send() on the response to return the string "Hello World!"

res.send-

In the app, we have written a GET request- a GET request will read the data on the specified URL path (for ‘/’ means the base path)

  • Here, res- response and req- request.
  • res.send is the respond send by the server to the client when client go the url path mentioned

OUTPUT we got when we visited the url(http://localhost:4444/) mentioned-

send

req.query -

  • req.query is the request made to the browser to send the data to the server.
  • Data comes in the object of request(req).
  • req.query is an object that stores data sent in the URL after a ?. Example: /greet?name=John{ name: 'John' }
  • And then to access the url in browser we have to give res.send
app.get('/greet',(req,res)=>{
        const{name}=req.query;
        //we have destructured the name from the url path using query parameter
        res.send(`hii after requesting from browser to send
         name- "${name}" to the server`);
        })
Enter fullscreen mode Exit fullscreen mode

OUTPUT after “getting” data from the url path using req.query and showing it on the browser using res.send

query

req.params-

Now, the another way to get the data be requesting is- req.params

it takes “key/:value” like this.

//in browser url path key/value are written without ':' unlike mentioned 
//in the get request
app.get('/movies/:movie',(req,res)=>{
        const{movie}=req.params;
        res.send(`the data requested using req.params is -${movie}`)
    })
Enter fullscreen mode Exit fullscreen mode

OUTPUT-
output

GET REQUEST IMPLEMENTATION AFTER STARTING A SERVER USING EXPRESS.JS

code

POST REQUEST (req.body, middleware)-

IT IS USED TO GIVE SOME DATA (CREATE/ ADD)

  • The data in POST request is hidden from user as it not shown in the url.
  • To use post request we used POSTMAN, and the res.send is shown in postman only as it is an alternative for browser
  • Data of post request is called “Payload”
  • In backend the data of payload is seen in “body” in postman
  • Whenever the server is restarted , we lost the added data (by post) hence we need databases.
app.post('/add',(req,res)=>{
        cost {name,id}= req.body;
        console.log(req.body);
        res.send(`new person- ${name}`);

})
Enter fullscreen mode Exit fullscreen mode

In the above code, we are using a POST request, at url ”localhost:4444/add” .If this url exists, its callback function is called.

MIDDLEWARE-

Middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

-Functions that run between a request and a response, e.g., parsing request body, authentication, logging.

-Hence it is like a layer or barrier that will run before the user gets the data from the server

-the data added using post was an encoded data send in the request body, hence it needs to be decoded by server.

middleware
req.body-

  • it is used with post request, it requests the data from the body that was added using postman
  • req.body will also has an object of name and age
  • Here , the res.send will show us the response in the body of the postman.

postman

Now, to get the data , that was added with the help of the post request, we use-

  1. get request
  2. a way to add data in a data structure (or DOM manipulation, so the data won’t get lost once server restarted)
  3. work in the callback function of post and get request to give and acquire data respectively

result

OUTPUT IN POSTMAN FOR GET REQUEST-

postman

OUTPUT IN TERMINAL-

terminal

OUTPUT IN BROWSER FOR GET -

output



ERROR-

BUT, once the server is restarted it gives error, because the data get lost that was added using post request, therefore, we require databases

error

SEND FILE AS A RESPONSE TO A PATH

In order to send a file as a response to the browser (client) , we first need the path to that file on the server. For that we use a built-in module of Node.js called path .

“PATH” module is utilised for working with file and directory path , making it easier to write code independent of system used upon.

const path= require('path')
Enter fullscreen mode Exit fullscreen mode

The function that we will use from path module is- path.join

  • It joins the path of different file and directory, without making it difficult to connect through concatenation and making it platform independent
  • path.join function takes the path and file name and join it
const pathOfFile= path.join(__dirname, '/index.html')
Enter fullscreen mode Exit fullscreen mode

here the __dirname is the path to the present directory of the system and joining it with the index.html file present in same directory.

Here, this pathOfFile will help us to locate the file and further send it as a res .

res.sendFile-

To send a file we cannot simply use res.send as it sends a single response but not any file, image or documents ,etc. .

Instead we use an Express.js function - res.sendFile that helps to send static files provided a HTTP response to the client.

app.get('/file',(req,res)=>{
        res.sendFile(path.join(__dirname,'/index.html);
}
Enter fullscreen mode Exit fullscreen mode

As a response on the browser we get-

response

Here is what we wrote to get this response-

code

⚠️

But what if our index.html file had style.css file and script .js file linked. Will those also work with in relation to index.html file being requested from our server ?

—NO, because a js and css file, in-fact any file is also a request on the server, hence they also need to be inclusive of the response of the GET request when requested at their path route.

issue

Therefore, we use GET request for all the files that we need as a response using res.sendFile

request

But what if there are hundreds of files that we want to send to the browser? It doesn't make sense to write a request for each file that needs to be sent, as it's time-consuming and makes it difficult to track which files have been handled.

Therefore we have- SERVING STATIC FILES

SERVING STATIC FILES-

To serve static files such as images, CSS files, and JavaScript files, we use the  express.static built-in middleware function in Express.

-Firstly a folder (usually under the name ‘static’) needs to be made in the directory.

-The static folder contains all the files that needs to be requested by the client

-It should have an .html file in order to show the response on the browser

static

Middleware-

app.use(express.static(path.join(__dirname,'static')));
Enter fullscreen mode Exit fullscreen mode

This middleware is a header, which means, we cannot send a GET request at path (’/’) , because express.static did that for us.

Hence, when we go the http://localhost: ${PORT} , it would launch a .html file that was present in the “static” folder and other linked files like javascript and CSS file.

OUTPUT -

result

Now, with the help of above knowledge we can create a basic todo app :)

Top comments (4)

Collapse
 
naman_arora_6e4fb5d60690d profile image
Naman Arora

Wow excellent work 👏🏻

Collapse
 
renam_singla_fb52a400f07e profile image
renam singla

Thankyou Naman

Collapse
 
kshitij_jha_464e2f4b972b7 profile image
Kshitij Jha

Great 💯💯💯

Collapse
 
renam_singla_fb52a400f07e profile image
renam singla

Thankyou so much