Sending Data with POST Requests to a NestJS Backend



·

In the previous tutorial, we focused on making a GET request from an Ionic application to a NestJS backend. A GET request is generally pretty simple, as all we are doing is making a generic request to a specific URL which will then return a response.

In this tutorial, we are going to cover how we can send data from our Ionic application to the NestJS backend by using a POST request. Unlike a GET request, a POST request allows us to send a data payload along with the request, which we can then do whatever we like with it on the backend.

The example we have been building on involves a service that allows us to retrieve messages/quotes. We are going to continue on with that theme in this tutorial, and extend our server to allow us to (hypothetically) add our own new messages/quotes. We will not actually be storing the messages that the server receives in this example, we will just be focusing on what is required to send the data to the server (we will cover storing server-side data in a future tutorial).

Before We Get Started

Last updated for NestJS 5.0.0

This tutorial continues on from the previous two tutorials:

  1. An Introduction to NestJS for Ionic Developers
  2. Using Providers and HTTP Requests in a NestJS Backend

These tutorials covered setting up a basic Ionic application using NestJS as the backend and making use of services/providers in NestJS to fetch data from an API with an HTTP request.

Although these tutorials focus on integrating with an Ionic/Angular application, you do not necessarily need to use Ionic/Angular in order to understand these tutorials – you would just need to modify the steps for integrating the front-end with the NestJS back-end. You also do not have to have read the previous tutorials to understand the concepts we will be covering in this tutorial, however, if you want to follow along with the examples used then you will need to complete the previous tutorials.

1. Create a Data Transfer Object (DTO) Schema for Adding Messages

In order for our NestJS server to accept data via a POST request, we need to define a Data Transfer Object Schema. It probably sounds a lot more complex than it is – basically, we just need to create a class or interface that describes the structure of the data we want to send.

You can create a DTO either through defining a class:

export class ExampleDto {
	title: string;
	description: string;
	rating: number;
}

or through defining an interface:

export interface ExampleDto {
    title: string;
    description: string;
    rating: number;
}

The NestJS documentation recommends that classes are used for defining DTOs, so you may as well just stick with that. If you are already familiar with types/interfaces, then the examples above should look very familiar. All we are saying is that the data we are sending will be an object that contains a title that is a string, a description that is a string, and a rating that is a number. Let’s create our DTO.

Create a file at src/messages/message.dto.ts and add the following:

export class MessageDto {
    content: string;
    submittedBy: string;
}

For our example message, we are just going to send an object that contains a content property and a submittedBy property.

2. Add a POST Handler to the Messages Controller

With the structure of our data defined, we can now set up the POST handler in our Messages controller. If you recall, we already have the following GET handler set up:

    @Get()
    getMessages(){
        return this.quotesService.getQuotes();
    }

Since this is inside of the messages controller, when we make a GET request to:

http://localhost:3000/messages

The handler above will be triggered. However, we are building a RESTful API, where the type of request we make to a particular endpoint determines the result we get. That means that we can also define a POST handler that is triggered when we hit:

http://localhost:3000/messages

with a POST request, and the result will be different to the GET handler. Let’s add that now.

Add the following imports to src/messages/messages.controller.ts:

import { Controller, Get, Post, Body, Param } from '@nestjs/common';
import { MessageDto } from './message.dto';

Notice that we have added Post and Body as well as our MessageDto.

Add the following handler to src/messages/messages.controller.ts:

    @Post()
    createMessage(@Body() message: MessageDto){
        console.log(message);
        return message;
    }

This handler will be activated whenever we make a POST request to /messages. When we make that POST request, we send a “payload” or “body” along with that request which contains all of the data we are sending. We grab this by using @Body inside of our parameters for the handler, and we assign it to message which is given a type of the DTO that we created.

Inside of this function, we will then be able to access the data that was sent from the application through the message variable – which would contain both the content and the submittedBy properties. We can do whatever we like with the data at this stage, and typically we would store it in a database somewhere. However, for this example, we are just going full circle and sending the same data that was submitted back as a response (just so that we can see that it is all working as expected).

3. Make the POST Request

Now we just need to update the front end of our application to send a POST request to:

http://localhost:3000/messages

which contains data that matches our message DTO. As I mentioned, we are using Ionic/Angular for this example, but you could execute this POST request using anything.

Add the following method to src/app/services/message.service.ts:

  createMessage(message): Observable<Object> {

    return this.http.post('http://localhost:3000/messages', {
      content: message.content,
      submittedBy: message.submittedBy
    });

  }

This is very similar to the GET request, except that we have an additional parameter as well as the URL which defines the data that we are sending along with the request. In this case, that is an object with a content property and a submittedBy property (which conforms to our message DTO).

Now we just need to trigger that method.

Modify src/app/home/home.page.ts to reflect the following:

import { Component, OnInit } from '@angular/core';
import { MessagesService } from '../services/messages.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {

  constructor(private messages: MessagesService){

  }

  ngOnInit(){

    let testMessage = {
      content: 'Hello!',
      submittedBy: 'Josh'
    };

    this.messages.createMessage(testMessage).subscribe((res) => {
      console.log(res);
    });

  }

}

This will launch the POST request as soon as the home page is intialised. Since we are just logging out the response, once you launch the application you should see something like this in the console:

Response in console from a NestJS server

So, we have successfully managed to send some data from our Ionic application to our NestJS server, and then we were able to send that data back again to the Ionic application.

Summary

In a more realistic example, rather than just parroting the data back to the Ionic application we would perhaps add that data into some kind of database on the backend and then return some kind of success response to the user. As I mentioned, we will do something like this in a future tutorial, but the example we have gone through in this tutorial is an effective demonstration of how we can send data to a NestJS server.

What to watch next...