Home » Node.js

How to send data in JSON format from server?

In this article, we are going to learn how to send data in JSON format from server?
Submitted by Manu Jemini, on November 17, 2017

Whenever we need data to process further, we request server to send data and the only format we mostly use is JSON (JavaScript Object Notation) a basic format that can easily being understand by most of the programming languages in web development.

So, in this tutorial we are going to understand how to send data in JSON format through our server?

We are using cors for cross domain connection, so just in case you want fetch data in cross domain connection, it will allow you to do that.

NOTE: You will need to install cors for this task. open command prompt and type "npm i cors"

Server file

var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
var persons = [
		{name: "Abhsihek Sharma", ID: 1,city:"Dabra"},
		{name: "Vikram Diwakar", ID: 2,city:"Bhind"},
		{name: "Manu Jemini", ID: 3,city:"Gwalior"},
		{name: "Dushyant Chauhan", ID: 4,city:"Dabra"}
		];
		
app.get('/, (req,res) => {
	res.json(person);
})

app.listen(3000);

Here we have come up with a very fundamental server in express.js.

  • We tell express to include express library and store its reference in variable express.
  • We need to allow CROSS DOMAIN http calls, hence using cors library.
  • Second-step is to tell express library to quickly initiate a server for us.
  • Express not only make a server but also give us a reference to do lots of manipulation.
  • Third, step is to use Cors, and then we do so.
  • Fourth, step is to listen for a Get request and sending the response in JSON format. Our response in Person array.
  • Then, we have to tell express to listen on the port 3000 after having a listener for the get request.
send data in JSON format from server

I am using a chrome extension for JSON-Viewer. Your result could be little ugly. This is how to do it.

Do comment if any query.




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.