13-Nodejs Course 2023: Request Payload
Tags: node, typescript, mongodb, fastify
Published: 2022-10-30 09:32:29

---
title: 13-Nodejs Course 2023: Request Payload
published: true
description: 
series: Nodejs Course 2023
tags: nodejs, typescript, mongodb, fastify
#cover_image: 
# Use a ratio of 100:42 for best results.
---

## Request Payload

So we talked in our lesson about request data types and we saw the request url data in action, now let"s see how we can get the request payload data.

## Request Body

The request body is the data that we send to the server in the request body, it can be in the form of JSON, XML, or any other format.

## Testing Request Body

Now we need to try the request body in action, but request body (payload) can only be available in POST, PUT, PATCH, and DELETE requests.

So to try this we can use [Postman](https://www.postman.com/downloads/), and we can send a request body in the body tab.

Just download and install it in your computer, now let"s open it.

## Postman

Once you"re ready with postman, create a new collection and name it `Ninja Node`, then create a new request and add to it the following url `http://localhost:3000/users` with request method `POST`.

Now let"s head to our `users` module and create a `create-user` controller

```ts
// src/app/users/controllers/create-user.ts

export default function createUser(request: any) {
    return request.body;
}
```

Now let"s import the controller in our `users` module and add it to the routes

```ts
// src/app/users/routes.ts
import router from "core/router";
import createUser from "./controllers/create-user";

router.post("/users", createUser);
```

Now let"s head to postman and send a request, click on the `Body` tab then select `raw` then select type `JSON`, in the text input add the following code

```json
{
    "name": "John Doe",
    "age": 30
}
```

Now click on the `Send` button, you should get the following response

```json
{
    "name": "John Doe",
    "age": 30
}
```

And that"s it!

## Uploading Files and Form Data

As we mentioned earlier, the request payload (body) can be json or a form data, the form data type will be the one we use to upload files to the server, but we need first to add a package to handle this for use, therefore we"ll use [fastify-multipart](https://github.com/fastify/fastify-multipart).

## Installing fastify-multipart

To install fastify-multipart, run the following command

```bash
yarn add @fastify/multipart
```

Now let"s register the plugin in our `core/application.ts` file

```ts
// src/core/application.ts

// 👇🏻 Import the plugin
import multipart from "@fastify/multipart";
import Fastify from "fastify";
import router from "./router";

export default async function startApplication() {
  const server = Fastify();

// 👇🏻 Add the following code
  server.register(multipart, {
    attachFieldsToBody: true,
  });

  router.scan(server);

  try {
    // 👇🏻 We can use the url of the server
    const address = await server.listen({ port: 3000 });

    console.log(`Start browsing using ${address}`);
  } catch (err) {
    server.log.error(err);
    process.exit(1); // stop the process, exit with error
  }
}
```

Now let"s move back to postman and this time we"ll select the `form-data` type, then add the following fields

- `name` with value `John Doe`
- `age` with value `30`
- `file`: type `file` and select a file

Open the `createUser` controller and now we"ll need to console log the request body to see what we get

```ts
// src/app/users/controllers/create-user.ts

export default function createUser(request: any) {
    console.log(request.body);
    return {
        done: true
    }
}
```

You should see something like this in your console

```json
{
    "name": "John Doe",
    "age": 30,  
    "file": {
    "fieldname": "file",
    "filename": "3- Create New Project.png",
    "encoding": "7bit",
    "mimetype": "image/png",
    "file": "FileStream" {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      bytesRead: 667277,
      truncated: false,
      _read: [Function (anonymous)],
      [Symbol(kCapture)]: false
    },
    fields: [Circular *1],
    _buf: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 05 00 00 00 02 d0 08 06 00 00 00 cf 7d dd 56 00 00 00 09 70 48 59 73 00 00 0e c4 00 00 0e 
c4 01 ... 667227 more bytes>,
    toBuffer: [AsyncFunction: toBuffer]
  },
  name: {
    fieldname: "name",
    mimetype: "text/plain",
    encoding: "7bit",
    value: "hasan",
    fieldnameTruncated: false,
    valueTruncated: false,
    fields: [Circular *1]
  }
}
```

Now we're totally fine with the request body, all set and clear.

## Conclusion

In this lesson we learned how to get the request payload data, we saw how to get the request body data and how to get the form data and files.

## 🎨 Project Repository

You can find the latest updates of this project on [Github](https://github.com/hassanzohdy/nodejs-2023)

## 😍 Join our community

Join our community on [Discord](https://discord.gg/vtZE9YzaFz) to get help and support (Node Js 2023 Channel).

## 🎞️ Video Course (Arabic Voice)

If you want to learn this course in video format, you can find it on [Youtube](https://www.youtube.com/playlist?list=PLGO8ntvxgiZMJc7RN2lIq9WmMOlWZGzmz), the course is in Arabic language.

## 💰 Bonus Content 💰

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

- [Event Driven Architecture: A Practical Guide in Javascript](https://dev.to/hassanzohdy/event-driven-architecture-the-best-paradigm-that-i-love-to-work-with-in-javascript-and-node-js-1gnk)
- [Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript](https://dev.to/hassanzohdy/best-practices-for-case-styles-camel-pascal-snake-and-kebab-case-in-node-and-javascript-55oi)
- [After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
](https://dev.to/hassanzohdy/after-6-years-of-practicing-mongodb-here-are-my-thoughts-on-mongodb-vs-mysql-574b)
-

Packages & Libraries

- [Collections: Your ultimate Javascript Arrays Manager](https://dev.to/hassanzohdy/collections-your-ultimate-javascript-array-handler-3o15)
- [Supportive Is: an elegant utility to check types of values in JavaScript](https://dev.to/hassanzohdy/supportive-is-an-elegant-utility-to-check-types-of-values-in-javascript-1b3e)
- [Localization: An agnostic i18n package to manage localization in your project](https://dev.to/hassanzohdy/mongez-localization-the-simplest-way-to-translate-your-website-regardless-your-favorite-framework-4gi3)

 React Js Packages

- [useFetcher: easiest way to fetch data in React Js](https://dev.to/hassanzohdy/usefetcher-the-easiest-way-to-fetch-data-in-react-45o9)

Courses (Articles)

- [React Js: Let"s Create File Manager With React Js and Node Js](https://dev.to/hassanzohdy/lets-create-a-file-manager-from-scratch-with-react-and-typescript-chapter-i-a-good-way-to-expand-your-experience-5g4k)