Skip to main content

In this section we will talk about 🔢data🔢! ✨

You can download the end product from my github! Click here!

  • (A) data we receive in a request,
  • (B) data we will send back (ie responses)

(A) How to get data from requests sent to us!

In order to be able to use the data we 'recieve' we need some configuration. Look at (1) to (3) for the configuration!

// (1) we need this for parsing JSON data
// (ie then we can use / receive the JSON data)
app.use(express.json());

// (2) we need this for parsing URL-encoded form data
// (ie then we can use / receive the form data)
app.use(express.urlencoded({ extended: false }));

// (3) this helps serve static files if user request from our endpoint
app.use(express.static(path.join(__dirname, 'public')));

Afterwhich we can use the data we recieve! These 2 lines of code allows us to receive 2 types of data:

  1. JSON Data
  2. URL Encoded Form Data

We will also talk about another type of commonly received data:

  1. Query Parameters

(A.1) What is JSON Data? ✨

A good example is : {"name": "John Doe", "age": 30, "city": "New York"}

This middleware is used in Express.js applications to parse URL-encoded form data from incoming HTTP requests. It's commonly used when handling HTML form submissions or other requests that send data in URL-encoded format.

  • Format: JSON (JavaScript Object Notation) is a lightweight data interchange format. It consists of key-value pairs, where keys are strings and values can be strings, numbers, arrays, objects, or booleans. JSON objects are enclosed in curly braces .
  • Content-Type: Requests containing JSON data typically have a Content-Type header of application/json.

Let's ChecK if we can get JSON Data! (req.body) 🎀

Let's check if it works by commenting out each individual line from (1) to (3) and then trying to console.log req.body!

const getBookings = function (req, res) {
console.log(req.body);
res.send('Here is all your bookings!');
};

in Bruno, select body > json() get json body using bruno

it should return

in your console!
{
hello: '123';
}

However if you try to comment out (1) [app.use(express.json())], you will not be able to recieve the data! You'll get undefined! - ie we were not able to receive our request data!

However when we uncomment (2) without (1) we can still get back the req.body BUT it's an empty object!

(A.2) What is URL-encoded Form Data? ✨

This middleware is used in Express.js applications to parse URL-encoded form data from incoming HTTP requests.

It's commonly used when handling HTML form submissions or other requests that send data in URL-encoded format.

  • Format: URL-encoded form data consists of key-value pairs encoded as strings, separated by '&' characters, and where keys and values are URL-encoded.

  • Content-Type: Requests containing URL-encoded form data typically have a Content-Type header of application/x-www-form-urlencoded.

How does express.urlencoded() work?

When included in an Express.js application using app.use(express.urlencoded()), this middleware parses the URL-encoded form data in the request body and makes it available in req.body as a JavaScript object.

Let's Check we can get URL Encoded Form Data! 🎀

const postBooking = function (req, res) {
// Accessing form data from req.body
const formData = req.body;

// Do something with the form data
console.log('Received form data:', formData);

// Respond to the client
res.send('Thanks for the new booking!');
};

in Bruno, select form option > send in! get form data using bruno

it should return

in your console!
Received form data: [Object: null prototype] { name: 'faith', age: '16' }

However if you try to comment out (2) - [app.use(express.urlencoded({ extended: false }));], you will not be able to recieve the data!

(A.3) What is Query Parameters? ✨

Query parameters are key-value pairs appended to the end of a URL.

They are typically used in GET requests to pass data to the server. Commonly used for "filtering" data.

Query parameters are separated from the URL path by a question mark (?), and multiple parameters are separated by ampersands (&). Each parameter consists of a key and a value, separated by an equals sign (=).

Let's set it up!

  1. Create a unique route for "searching" (Recommended)
app.get('/search', (req, res) => {
res.send('This is my search route!');
});
  1. Getting the query params!
app.get('/search', (req, res) => {
// Accessing query parameters
const type = req.query.type;
const page = req.query.page;

// Do something with the query parameters
console.log('Type:', type);
console.log('Page Number:', page);
// Send a response
res.send('This is my search route!');
});

in Bruno, select query > type in key value pair > send in!

get query params

Alternatively you can open up a browser and go to this link!

https://example.com/search?type=ASC&page=1

it should return

in your console!

Type: ASC
Page Number: 1

This is depending if you did state query parameters or not!

To take note that in the code attached for advanced setup, i have "organized" the code into their respective Route and Controller!

(B) Responding to a request made to our Express Server!

1. res.render():

Render a view template and send the resulting HTML to the browser. (Usually used for EJS but we've not learnt it - can skip!)

2. res.redirect():

Tell the browser to redirect to another page.

3. res.json():

Send a JSON response (used when we communicate via AJAX).

4. res.send():

A versatile method used in Express.js to send a response back to the client.

It can send various types of responses, such as HTML, plain text, JSON, Buffers, or even HTML files.

❗️ it's a good time to read up on Bruno now! it helps with testing that your routes are working!