Dismiss Notice

Register now to be one of the first members of this SharePoint Community! Click here it just takes seconds!

Dismiss Notice
Welcome Guest from Country Flag

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

Discussion in 'SharePoint Blogs' started by krishna-janardhanan,, Apr 1, 2017.

  1. krishna-janardhanan,

    krishna-janardhanan, Guest

    Blog Posts:
    0
    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

    [​IMG]

    [​IMG]

    Continue reading...
     

Share This Page

LiveZilla Live Chat Software