Exercise 2: Returning JSON

  1. Let's go back to our server.js file from Exercise 1, Building a Basic Hapi.js Server.

Use the exercise-b2 folder for your reference at Code/Lesson-2.
  1. To return JSON for our / route, all we need to change is our returned string to an object:
handler: (request, reply) => 
{
return reply({ message: 'hello, world' });
}
  1. Stop the server by going to the Terminal where the server is running and pressing Ctrl + C. Then, start the server again to effect the changes by running the following command:
node server.js
  1. Now go back to Insomnia and do another GET request. You can see that this is effectively changed into a JSON string:
{
"message": "hello, world"
}

This comes out-of-the-box in Hapi.js, while with some frameworks, such as Express.js, you have to use a json function to do the conversion.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset