DEV Community

Hasan Zohdy
Hasan Zohdy

Posted on

13-Nodejs Course 2023: Request Payload

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, 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

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

export default function createUser(request: any) {
    return request.body;
}
Enter fullscreen mode Exit fullscreen mode

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

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

router.post("/users", createUser);
Enter fullscreen mode Exit fullscreen mode

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

{
    "name": "John Doe",
    "age": 30
}
Enter fullscreen mode Exit fullscreen mode

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

{
    "name": "John Doe",
    "age": 30
}
Enter fullscreen mode Exit fullscreen mode

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.

Installing fastify-multipart

To install fastify-multipart, run the following command

yarn add @fastify/multipart
Enter fullscreen mode Exit fullscreen mode

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

// 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
  }
}
Enter fullscreen mode Exit fullscreen mode

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

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

export default function createUser(request: any) {
    console.log(request.body);
    return {
        done: true
    }
}
Enter fullscreen mode Exit fullscreen mode

You should see something like this in your console

{
    "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]
  }
}
Enter fullscreen mode Exit fullscreen mode

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

๐Ÿ˜ Join our community

Join our community on Discord 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, 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

Packages & Libraries

React Js Packages

Courses (Articles)

Top comments (0)