This website uses cookies to enhance the user experience

Requests and Responses

Share:

Requests and responses play an integral role in any web application and AdonisJS provides robust tools to handle them. AdonisJS treats every single request as an HTTP request, following the rules of the HTTP/1.1 specification. In this chapter, we will delve into handling requests and responses using AdonisJS.

Understanding Requests

Every time a client (like a web browser) makes a call to the server, it sends a 'request'. This request may contain numerous details like the URL, the HTTP method used (like GET, POST, etc), headers, and body. AdonisJS provides a Request object that encapsulates all these details, and offers various methods to access and manipulate them.

For instance, let's consider a scenario where the Marvel universe uses AdonisJS for their superhero management system. Whenever Spiderman wants to upload his latest photo, he makes a request to the server. This request can be accessed in the controller as follows:

Route.get('upload/photo', 'PhotoController.upload')

// In PhotoController.js
class PhotoController {
  upload ({ request }) {
    const photo = request.input('photo')
    // proceed with the photo upload logic
  }
}

The request.input('photo') line retrieves the 'photo' data from the request. If Spiderman sends his photo with the key 'photo', it will be fetched here.

Sometimes, Iron-Man might want to send multiple photos. In that case, the request.all() method comes in handy as it fetches all the data sent with the request.

Route.get('upload/photos', 'PhotoController.uploadMultiple')

// In PhotoController.js
class PhotoController {
  uploadMultiple ({ request }) {
    const allPhotos = request.all()
    // proceed with the multiple photo upload logic
  }
}

Furthermore, AdonisJS request object allows access to other elements such as headers, cookies, URL params, etc. Let's say Thor accesses an API endpoint with a header set as "Authentication". This header can be fetched using request.header() method as follows:

Route.get('get/hammer', 'HammerController.fetch')

// In HammerController.js
class HammerController {
  fetch ({ request }) {
    const token = request.header('Authorization')
    // proceed with checking the token validity
  }
}

Working with Responses

Once the server has processed a request, it needs to send back a 'response'. The Response object provided by AdonisJS ensures the standard conventions of HTTP are followed while providing intuitive methods to customize responses.

For instance, taking the above example, once Spiderman uploads his photo successfully, the server needs to acknowledge it. Here's an example:

Route.get('upload/photo', 'PhotoController.uploadResponse')

// In PhotoController.js
class PhotoController {
  uploadResponse({ request, response }) {
    const photo = request.input('photo')
    // proceed with the photo upload logic
    response.status(200).send('Photo Uploaded Successfully')
  }
}

The response.status(200).send('Photo Uploaded Successfully') line sends a response with status code 200 (which means 'OK') and a message indicating the photo was uploaded successfully.

Apart from sending custom status and text, the Response object allows sending different types of responses such as JSON, View, Download, Stream, and Redirect.

To illustrate, suppose Captain America receives a JSON response with details when he fetches the list of Avengers. This can be done as follows:

Route.get('avengers-list', 'AvengersController.getList')

// In AvengersController.js
class AvengersController {
  getList({ response }) {
    const avengers = [
      { id: 1, name: 'Iron Man'},
      { id: 2, name: 'Thor'},
      { id: 3, name: 'Hulk'}
      //...
    ]
    response.status(200).json(avengers)
  }
}

The response.status(200).json(avengers) line sends a JSON response with status code 200, which contains the list of Avengers.

AdonisJS provides a seamless way to handle requests and responses in a standardized, yet flexible way, making it an appealing choice for web developers. In the following chapters, we will further explore other aspects of AdonisJS like Middleware, Error Handling, etc. so stay tuned!

0 Comment


Sign up or Log in to leave a comment


Recent job openings

South Africa, Claremont, Western Cape

Remote

Full-time

posted 19 hours ago

India

Remote

Full-time

JavaScript

JavaScript

TypeScript

TypeScript

+4

posted 19 hours ago

India, Noida, UP

Remote

Full-time

Python

Python

JavaScript

JavaScript

+5

posted 19 hours ago

India

Remote

Contract

JavaScript

JavaScript

TypeScript

TypeScript

+4

posted 19 hours ago

Philippines, Mandaluyong City, Metro Manila

Remote

JavaScript

JavaScript

SQL

SQL

+8

posted 19 hours ago