You can get a request digest by sending a POST
request to
http://server/site/_api/contextinfo
with only an accept: 'application/json;odata=verbose'
header.
Apparently there is some confusion about what I am saying.
When SharePoint generates a page, it adds a hidden element with the ID __REQUESTDIGEST
. Usually, when you are writing code to call the REST API, and that code is hosted on a page served by SharePoint, you use
document.getElementById('__REQUESTDIGEST').value
in order to get the value of the request digest, so that you can then use it as the value of the X-RequestDigest
header in your REST call.
If your code is not running on a page served by SharePoint, that hidden element will of course not be there, so trying to do
document.getElementById('__REQUESTDIGEST').value
will not work.
HOWEVER, there is another way to get that value. Now, I've never used the Headers
object, but following the pattern of OP's code sample, if you do this:
const url = 'http://sp2016:5155/_api/contextinfo';
const requestDigestPostSettings = {
method: 'POST',
headers: new Headers({
'accept': 'application/json;odata=verbose'
})
}
fetch(url, requestDigestPostSettings).then(response => {
const requestDigestValue = response.d.GetContextWebInformation.FormDigestValue;
// now you can use the requestDigestValue in the X-RequestDigest header in your _next_ REST call
});
NOTE: I just tested this through Postman on a SP2013 site. It seems that OP is using SP2016? So I'm not sure if the exact structure of the response object will be d.GetContextWebInformation.FormDigestValue
, but the digest value will be in the response somewhere.
The point being that you can get a request digest value by making a REST call to the site if you cannot get it through document.getElementById
, which you can then turn around and use in the X-RequestDigest
header of a subsequent REST call where you do what you are really trying to do in the first place.