I'm using SharePoint's REST APIs to build a simple application that displays all items of a list and includes a form to create a new list item. All users are able to view the items, but only a few users can't create a new list item because of a 401 unauthorize error. Trying to retrieve the Form Digest Value also results in a 401 unauthorize error because it's a POST request. Here are the functions to create a new list item and to retrieve the form digest value:
const createItem = async (data, url) => {
const digestVal = await getFormDigestValue().then(data => data.d.GetContextWebInformation.FormDigestValue);
return $.ajax({
url,
type: "POST",
headers: {
// Accept header: Specifies the format for response data from the server.
"Accept": "application/json;odata=verbose",
//Content-Type header: Specifies the format of the data that the client is sending to the server
"Content-Type": "application/json;odata=verbose",
// X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
"X-RequestDigest": digestVal
},
data: JSON.stringify(data)
})
}
const getFormDigestValue = () => {
return $.ajax({
url: 'https://example.com/_api/contextinfo',
method: 'POST',
headers: { Accept: 'application/json; odata=verbose' }
});
}