Monday 2 May 2016

Node JS with SharePoint


What is Node JS and why?

Node JS is a java script based web development platform, where we can develop and host Web applications and Web Services. 

Let’s assume a scenario where we need to access SharePoint resources (list/library data) on mobile app or some other web application. The first thing comes to our mind is a web service.  Now we have two options to implement a web service:
1. WCF RESTful Service in C# and
2. NODE JS Web API.
The reasons to choose Node JS web service over WCF service are:
1. Open source
2. Lightning Fast Speed
3. JavaScript based
4. Comparatively faster than WCF
5. Easy to Unit Test

Prerequisites

  1. Node JS – Download and Install latest version of Node JS from here. 
  2.  Custom packages from GitHub – Download and install node packages as and when required. The cmdlets to install packages are explained in “Install Node packages” section. 
  3.  Visual studio/any other IDE

Supports only Basic or NTLM Authentication of SharePoint

To communicate with SharePoint, we are going to use a node package HTTPNTLM. It supports only NTLM authentication mode of SharePoint. If your SharePoint site supports claims based authentication, we may achieve it using a node package called request. ButI amnot going to explain it here.

Install Node Packages

Node packages can be installed using node console which will be available after installation of Node JS. Below are the packages that we need to install.

httpntlm

httpntlm package is used to communicate with SharePoint REST APIs. We just need to pass the credentials
$ npm install httpntlm --save

express

Express is a Node JS’s web application framework that provides a robust set of features for mobile and web applications
$ npm install express –save

cors

cors package allows a Web API to accept cross domain requests.
$ npm install cors –save

xml2js

Used to convert xml data into JSON format
$ npm install xml2js –save

deasync

Used to make synchronous calls to java script functions
$ npm install deasync –save

What is Express App

Express is a most popular web application framework in Node JS just like MVC in .NET.  If you are using Visual Studio, download a project template for Node JS form here. Create a new project of type ‘Basic Node.Js Express 4 Application’.



Replace the code in app.js with below code snippet.
If you are not using Visual Studio, create a JS file namedapp.js and put the below code snippet:

“use strict”
var express =require('express');
var app =express();
varroutes =require('./Routes')(app); //to be added in next step
app.listen(4444); // app.listen(<Port no>)

module.exports = app;

Routes

Routes are the application endpoints which redirects to specific web service depending upon the Request type (GET/POST) and URI.  Create a folder named Routes and add a file named index.js. Put below code: 

“use strict”
module.exports= function(app) {
varservices= require ('../Services');
varcors = require ('cors');
app.use(cors());
  //Services Routes 
app.get('/_api/getAllEmployees',cors(),Services.getAllItems);    
// app.post ('/_api/addEmployee',cors(),Services.addItem);  
}
Observe the above code snippet and find the routes.
Routes: '/_api/getAllEmployees' and /_api/addEmployee

Services

Now it’s time to access SharePoint resources using REST API. Let’s expand the above codeadd definition for Services.getAllItems. Add a new folder named Services and add a JS file named index.js and put below code in it:


“use strict”
var httpntlm = require('httpntlm');
var parseString = require('xml2js').parseString;
var deasync = require('deasync');
var siteURL = "http://<SiteCollectionName>", domainName = "<domain name>";
 
//1.Get All Employee Service 
exports.getAllItems = function (req, res) {
var httpResponse = { "statusCode": 500, result: undefined };
var url = siteURL + "/_api/web/lists/getByTitle('<ListName>')/items";
var headers = { "Accept": "application/json;odata=verbose", 
                "content-type": "application/json;odata=verbose;"
         };
httpntlm.get({
                url: url,
                contentType: 'application/json;odata=verbose',
                username: '<MyUsername>',
                password: '<MyPassword>',
                domain: '<DomainName>',
                workstation: '',
                headers:headers},
         function success(error, response) {
                 httpResponse.result = JSON.parse(response.body);                     
                 res.send(httpResponse);
            })//End of get
};//End of getAllItems
I am not writing the Code for post method here, that will allow you to get some hands-on experience on node JS.  :)

Run The Web API

You can run the web api using a cmdlet node as
$ node app.js
To test if it’s functioning or not, put the URL in browser and check the response:

 
http://<ServerName>:4444/_api/getAllEmployees

Summary

Node JS is a web hosting platform for Web sites and Web Services. Follow the steps as mentioned in this post and access the required SharePoint resources.
Any questions, comments and suggestions are most welcome! Have a great day ahead!

5 Steps to achieve Lazy Loading in SharePoint

Hello SharePointers!   Through this blog, I will walk you through a JS library implemented by me which helps us to load SharePoint list it...