June 23, 2022

SharePoint Framework (SPFx) - How to add Request Header while using PnP for SharePoint List CRUD Operations?

Introduction:

In this blog we will learn how can we add the Request Header while using PnP in SharePoint Framework (SPFx) web parts.

Problem Statement:

When we use the Fetch or Ajax requests in SPFx, we have option to add the Request Header to the REST API requests we are using, but when using PnP, there is no option to add the Request Header while performing CRUD operations in SharePoint.

For example, while using Fetch Request to get the list items, we can add the header as give in below code snippet:
 return fetch(APIUrl, {  
    credentials: 'same-origin',  
    headers: {   
         'Accept': 'application/json;odata=verbose',  
         'odata-version': ''   
    }  
   })  
    .then((res) => res.json())  
    .then((result) => {      
     return result.d.results;  
    },  
     (error) => {  
      console.error('Error:', error);  
     }  
    );  

But, to get the list items using PnP, we will use below code and we will not have option to add the headers:
 await web.lists.getByTitle('List Title').items.select("Title").then((response) => {  
    this.setState({ SiteTimeZoneOnly: response[0].TimeZone });  
 });  

Resolution:

How to add headers:

Step 1) Go to the .ts file of your web part.

Step 2) Now, go to the onInit method.

Step 3) Now, we can add the header in onInit method as given in below code snippet:
 protected onInit(): Promise<void> {  
   return super.onInit().then(_ => {  
    // other init code may be present  
    sp.setup({  
     spfxContext: this.context,  
     sp: {  
      headers: {  
        "X-ClientTag": "********"  
      }  
     }  
    });  
   });  
  }  

Here we have added 'X-ClientTag' header. You can also add comma separated multiple headers as shown in the below code snippet.
 sp.setup({  
     spfxContext: this.context,  
     sp: {  
      headers: {  
        "X-ClientTag": "********",  
        "Accept": "application/json;odata=verbose"  
      }  
     }  
    });  

Now your header is added successfully. You can verify the headers from Network tab of browser developer tool as shown in the below screenshot:

Conclusion:

This is how we can add Request Header in SPFx while using PnP to perform SharePoint list/library operations.

If you have any questions you can reach out our SharePoint Consulting team here.

No comments:

Post a Comment