In the earlier article, we saw how to setup a NodeJS application and start the development. As a continuation, let us see, how to create the SharePoint Context and access the SharePoint Sites.
The intention is to access the SharePoint objects and do some functionality from a Node JS application. i.e., a Separate standalone application which will do some action on our SharePoint Tenant.
To get the SharePoint Client Context, install the node-pnp-js and sp-pnp-js.
Let us take the earlier application itself for this continuation.
Install the following node modules.
npm install sp-pnp-js –save
npm install pnp-auth –save
npm install @pnp/logging @pnp/common @pnp/odata @pnp/sp –save
Update the Index.ts file as below.
import express, { Application, ErrorRequestHandler, Request, response, Response } from 'express';
import NodeFetchClient from 'node-pnp-js';
import * as pnp from 'sp-pnp-js';
const app: Application = express();
const PORT = process.env.PORT || 2000;
let url = "https://sppalsmvp.sharepoint.com/sites/MySiteCollection/";
let credentialOptions = {
username: 'sathish@sppals.com',
password: '*******'
};
app.get("/", async (req: Request, res: Response): Promise<void> => {
pnp.setup({
sp: {
fetchClientFactory: () => {
return new NodeFetchClient(credentialOptions, url);
}
}
});
try {
let list = await pnp.sp.web.lists.getByTitle('TempList').get();
console.log(list);
res.send(list);
}
catch (error) {
res.send(error);
}
});
app.use(function (err: any, req: Request, res: Response, next: ErrorCallback) {
res.status(err.status || 500);
res.send(err);
});
app.listen(PORT, (): void => {
console.log(`Server Running here https://localhost:${PORT}`);
});
Then on the command prompt, execute npm run dev to run the server.
If we browse, then the output will be as below.
Download the Source HERE
Happy Coding
Sathish Nadarajan
Leave a comment