JSON and JSONP requests using ExpressJs

Javascript Jul 26, 2015
Subscribe

JSON and JSONP requests using ExpressJs

Download from github

Intro

The following example shows how to simulate JSON and JSONP request / response using Node.js and Express.js.

First of all, you need to download and install node.js from the following link, later you need to create a new folder which is going to contain all project files, and launch the following command inside the new folder:

$ npm install express

The project is divded into two parts: the index.html which contains all requests to the server, server.js which is running inside node.js server process.

JSON request/response

The following code describes the JSON part of the example.

Client side

Index.html contains a link that makes an ajax request on every click.

the request send an object which contains a title and a message to the following url:

 http://localhost:3000/endpointJSON

Server side

server.js receives the data object sent by index.html and returns data to the client:

The following command starts the node.js server:

node PROJECT_PATH\server.js

CORS considerations

It’s possible that the previous code going to fail because browsers don’t allow Cross-Origin resource sharing:

XMLHttpRequest cannot load http://localhost:3000/endpointJSON?{%22title%22:%22title%22,%22message%22:%22message%22}. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

We need to use JSONP to avoid the problem.

JSON(P) request/response

JSONP is really a simple trick to overcome the XMLHttpRequest same domain policy. (As you know one cannot send AJAX (XMLHttpRequest) request to a different domain.)

Client side

The following code adds a new JSONP AJAX request to index.html:

The JSONP request add the javascript function which is going to contains the data returned by node.js server.

Server side

The following code adds a new handler to server.js that receives all JSONP requests:

Conclusion

The example shows how to simulate AJAX requests between client and server, it also shows how to avoid CORS error using JSONP.
That’s all for now, Cheers :).