How to add a SharePoint List Item using Express JS by passing Request Digest

Krishna KV
 
Team Leader, Aspire Systems
April 1, 2017
 
Rate this article
 
Views
4239

This article is about how to configure Express JS and pass the request digest for SharePoint to add a new list item.

Package.json

 {
   "name": "exp",
   "version": "1.0.0",
   "main": "index.js",
   "repository": {},
   "license": "MIT",
   "dependencies": {
     "body-parser": "^1.16.1",
     "compression": "^1.6.2",
     "cookie-parser": "^1.4.3",
     "express": "^4.14.1",
     "httpntlm": "1.7.4", 
     "cors": "2.8.1",
     "async": "2.1.5",
     "agentkeepalive": "3.1.0",
     "httpreq": "0.4.23", 
     "express-api-helper": "0.0.5",
     "request": "2.79.0"
   },
   "devDependencies": {}
 }

To create and update pass the Request-Digest

The below method will get the request digest and add the item to the SharePoint list.

 const express = require('express');
 let router = express.Router();
 let httpntlm = require('httpntlm');
 
 var ntlm = require('httpntlm').ntlm;
 var async = require('async');
 var httpreq = require('httpreq');
 var HttpsAgent = require('agentkeepalive').HttpsAgent;
 var keepaliveAgent = new HttpsAgent();
 
 var app = express()
 function getSPConfig() {
     return {
         url: "https://url-of-the-site/",
         username: 'username',
         password: 'password',
         domain: 'domain',
         workstation: '',
         headers: {
             "Accept": "application/json;odata=verbose",
             "content-type": "application/json;odata=verbose;"
         }
     }
 };
 
 router.post('/', function (req, res) {
 
     getDigest(function (json) {
         let opt = getSPConfig();
          opt.url= opt.url + "_api/web/lists/getByTitle('Testing')/items";
         let metdata = {
             __metadata: { 'type': 'SP.Data.TestingListItem' },
             Title: req.body.Title
         };
         console.log(metdata);
 
         console.log(json.d.GetContextWebInformation.FormDigestValue);
         opt.headers['X-RequestDigest'] = json.d.GetContextWebInformation.FormDigestValue
         opt.json =metdata;
         httpntlm.post(opt, function success(error, addResponse) {
             res.status(200).send("Added");
         });
     }, function error(err) {
         res.status(500).send(err);
     });
 
 });

App.js

 const express = require('express');
 const bodyParser = require('body-parser');
 const compression = require('compression');
 let port = 3000;
 let app = express();
 let router = express.Router();
 app.use(compression());
 app.use(bodyParser.json());
 app.use('/api', router); // Adding router middleware in the express js 
 
 let doc = require('./doc');
 router.use('/doc', doc);
 
 app.listen(port, (err, req, res, next) => {
        console.log(`server started at ${port}`);
 });
 

Doc.js

 const express = require('express');
 let router = express.Router();
 let httpntlm = require('httpntlm');
 
 var ntlm = require('httpntlm').ntlm;
 var async = require('async');
 var httpreq = require('httpreq');
 var HttpsAgent = require('agentkeepalive').HttpsAgent;
 var keepaliveAgent = new HttpsAgent();
 
 var app = express()
 function getSPConfig() {
     return {
         url: "https://sitecollectionurl",
         username: 'username',
         password: 'password',
         domain: 'domain',
         workstation: '',
         headers: {
             "Accept": "application/json;odata=verbose",
             "content-type": "application/json;odata=verbose;"
         }
     }
 };
 
 router.post('/', function (req, res) {
 
     getDigest(function (json) {
         let  opt = getSPConfig();
         let title=req.body.Title;
 
         console.log(json.d.GetContextWebInformation.FormDigestValue);
         opt.headers['X-RequestDigest'] = json.d.GetContextWebInformation.FormDigestValue
         opt.json = { __metadata: { 'type': 'SP.Data.TestingListItem' },title  };
         httpntlm.post(opt, function success(error, addResponse) {
             res.status(200).send("Added");
         });
     }, function error(err) {
         res.status(500).send(err);
     });
 
 });
 
 function getDigest(returnfun) {
 
             let spConfig = getSPConfig();
 async.waterfall([
     function (callback) {
 
         var type1msg = ntlm.createType1Message(spConfig);
 
         httpreq.post(spConfig.url + "_api/contextinfo", {
             headers: {
                 'Connection': 'keep-alive',
                 'Authorization': type1msg,
                 'accept': 'application/json;odata=verbose'
             },
             agent: keepaliveAgent
         }, callback);
     },
 
     function (res, callback) {
 
         if (!res.headers['www-authenticate'])
             return callback(new Error('www-authenticate not found on response of second request'));
 
         var type2msg = ntlm.parseType2Message(res.headers['www-authenticate']);
         var type3msg = ntlm.createType3Message(type2msg, spConfig);
 
         setImmediate(function () {
             httpreq.post(spConfig.url + "_api/contextinfo", {
                 headers: {
                     'Connection': 'Close',
                     'Authorization': type3msg,
                     'accept': 'application/json;odata=verbose'
                 },
                 allowRedirects: false,
                 agent: keepaliveAgent
             }, callback);
         });
     }
 ], function (err, response) {
     var json = JSON.parse(response.body);
     return returnfun(json);
 
 });
 }
 
 module.exports = router;
 

To Run the express api

Open Command prompt and execute bellow

npm install – to install the node dependencies

node app.js – to run the express js

nodemon app.js – to reload the express api while changing (install the nodemon globally -npm install –g nodemon)

Currently using postman to test the app

clip_image001

clip_image002

Author Info

Krishna KV
 
Team Leader, Aspire Systems
 
Rate this article
 
Krishna K.V has been working in IT Industry for over 7+ years. He holds a Master Degree in Information Technology. He is more interested to learn and share new technologies, ...read more
 

Leave a comment