Book Image

JavaScript and JSON Essentials - Second Edition

By : Bruno Joseph D'mello, Sai S Sriparasa
Book Image

JavaScript and JSON Essentials - Second Edition

By: Bruno Joseph D'mello, Sai S Sriparasa

Overview of this book

JSON is an established and standard format used to exchange data. This book shows how JSON plays different roles in full web development through examples. By the end of this book, you'll have a new perspective on providing solutions for your applications and handling their complexities. After establishing a strong basic foundation with JSON, you'll learn to build frontend apps by creating a carousel. Next, you'll learn to implement JSON with Angular 5, Node.js, template embedding, and composer.json in PHP. This book will also help you implement Hapi.js (known for its JSON-configurable architecture) for server-side scripting. You'll learn to implement JSON for real-time apps using Kafka, as well as how to implement JSON for a task runner, and for MongoDB BSON storage. The book ends with some case studies on JSON formats to help you sharpen your creativity by exploring futuristic JSON implementations. By the end of the book, you'll be up and running with all the essential features of JSON and JavaScript and able to build fast, scalable, and efficient web applications.
Table of Contents (20 chapters)
Title Page
Copyright and Credits
Dedication
Packt Upsell
Contributors
Preface
Index

Hosting JSON


In this section, we will be creating a node script that will allow us to send a JSON feedback to the user upon a successful request. Let's take a look at the app.js file that accomplishes this task:

const http = require('http');
const port = 3300;
http.createServer((req, res) => {
    res.writeHead(200, { 
      "Content-Type": "application/json"
    });
    res.write(JSON.stringify({
      greet : "Hello Readers!"
    }));
    res.end();
}).listen(port);
console.log(`Node Server is running on port : ${port}`)

The changes required to send JSON data are highlighted in the preceding snippet. The above script consists of a JSON object with greet as the key and Hello Readers! as the value. The object is first stringified as the responses provided are always in string or buffer form. Moreover, we need to provide the content-type as application/json. The Content-Type gets set inside the header of response so that the browser may identify the response type as mentioned.

Let's increase...