0
votes

I am trying to learn react and am creating a SharePoint Framework web part application. I am trying to retrieve the data from a list on the site using fetch from react. I am working in the hosted SharePoint workbench.

When I run this from a button click I am getting 403 forbidden. When I setup the same rest call in postman I get the expected data returned. I believe I need to add X-RequestDigest to the header, however document.getElementById("__REQUESTDIGEST") returns null. What I am doing wrong in the SharePoint workbench?

submit = e => {
 fetch(
  "https://MY_URL_HERE.sharepoint.com/_api/lists/getbytitle('MY_LIST_NAME_HERE')/items",
  {
    method: "GET",
    headers: {
      "Accept": "application/json;odata=verbose",
      "Content-Type": "application/json;odata=verbose",
      "odata-version": "",
      "IF-MATCH": "*",
      "X-HTTP-Method": "MERGE",
    }
  }
 ).then(response => console.log(response));
};
1

1 Answers

0
votes

SPFx provides a built-in httpclient to make REST API calls.

No, if you are in your SharePoint hosted workbench, then, to get list items, you don't need a request digest.

Modify your code as mentioned below:

Add the below import statement:

import { SPHttpClient, SPHttpClientResponse, SPHttpClientConfiguration } 
from '@microsoft/sp-http';

Now, instead of fetch, you can use the below code:

this.context.spHttpClient.get("https://MY_URL_HERE.sharepoint.com/_api/lists/getbytitle('MY_LIST_NAME_HERE')/items",  
      SPHttpClient.configurations.v1)  
      .then((response: SPHttpClientResponse) => {  
        response.json().then((responseJSON: any) => {  
          console.log(responseJSON);  
        });  
      });