Trying to create my first web part for SharePoint online that writes to a list. But when I do a post using jQuery ajax I receive an Unauthorized error. Any help you be greatly appreciated.
I am reusing some found code so maybe I'm missing something:
I first get the form digest:
var formDigest;
$.ajax({
async: false,
url: "https://#################/_api/contextinfo",
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"contentType": "text/xml"
},
success: function (data) {
debugger;
var requestdigest = data;
formDigest = data.d.GetContextWebInformation.FormDigestValue;
},
error: function (err) {
debugger;
alert(err.statusText);
console.log(JSON.stringify(err));
}
});
Then I try to post to the list:
$.ajax({
async: false,
url: "https://#################/_api/web/lists/getByTitle('TestList')/items",
method: "POST",
data: JSON.stringify({
'__metadata': {
'type': 'SP.Data.TestListListItem'
},
'Title': "TEST"
}),
headers: {
"Accept": "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": formDigest,
"X-HTTP-Method": "POST",
"X-FORMS_BASED_AUTH_ACCEPTED": "f"
},
success: function(data) {
alert("Item created successfully");
},
error: function(error) {
console.log(JSON.stringify(error));
}
});
When I try to do the insert I get a Unauthorized error.
Now I am able to do a get to the list but when I do a POST the error occurs.
X-HTTP-MethodandX-FORMS_BASED_AUTH_ACCEPTEDheaders? I've never used those headers when doing aPOSTto create an item. I do useX-HTTP-Methodwhen doing aPOSTto update an existing item, but it doesn't look like that's what you are doing there.