How to update a SharePoint list item using Express JS

Krishna KV
 
Team Leader, Aspire Systems
June 24, 2017
 
Rate this article
 
Views
2911

In this article we can see how to update a SharePoint list item using Express JS, by passing the request digest header. For adding item and configuration steps, refer the previous article https://www.sharepointpals.com/post/How-to-add-a-SharePoint-List-Item-using-Express-JS-by-passing-Request-Digest

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": {}
  }
 

app.js

 const express = require('express');
 const bodyParser = require('body-parser');
 const compression = require('compression');
 const port = 3000;
 const app = express();
 const router = express.Router();
 const httpntlm = require('httpntlm');
 const async = require('async');
 const httpreq = require('httpreq');
 const ntlm = require('httpntlm').ntlm;
 const HttpsAgent = require('agentkeepalive').HttpsAgent;
 const keepaliveAgent = new HttpsAgent();
 
 app.use(compression());
 app.use(bodyParser.json());
 app.use('/api', router); // Adding router middleware in the express js 
  function getSPConfig() {
         return {
             url: "https://your-sp-url/",
             username: '[User Name]',
             password: '[Password]',
             domain: '[Domain Name]',
             workstation: '',
             headers: {
                 "Accept": "application/json;odata=verbose",
                 "content-type": "application/json;odata=verbose;"
             }
         }
     };
 
     // method to get the RequestDigest header 
 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);
 
     });
 }
 
 router.put('/:id', (req, res) => {
     let httpResponse = { "statusCode": 500, result: undefined };
     let opt = getSPConfig();
     opt.url = opt.url + "_api/web/lists/getByTitle('Testing')/items(" + req.params["id"] + ")";
 
     httpntlm.get(opt, function (error, resp) {
         let data = JSON.parse(resp.body);
         opt.url = data.d.__metadata.uri;
         getDigest(function (json) {
 
             opt.headers["X-RequestDigest"] = json.d.GetContextWebInformation.FormDigestValue;
             opt.headers["X-HTTP-Method"] = "MERGE";
             opt.headers["If-Match"] = data.d.__metadata.etag;
 
             opt.json = { __metadata: { 'type': 'SP.Data.TestingListItem' }, Title: "Item Update at " + new Date() };
             httpntlm.post(opt, function (error, response) {
                 httpResponse.result = response;
                 res.send(httpResponse);
             });
         });
     });
 });
 
 app.listen(port, (err, req, res, next) => {
     console.log(`server started at ${port}`);
 });
 
 

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