Sharepoint 2013 via REST API: Error 403 Forbidden when trying to create item

前端 未结 3 764
孤独总比滥情好
孤独总比滥情好 2020-12-05 08:26

I\'m trying to create a simple list item with the rest api on Sharepoint 2013. My code:

$.ajax({
    url: siteUrl + \"/_api/web/lists/getByTitle(\'internal_L         


        
3条回答
  •  -上瘾入骨i
    2020-12-05 08:59

    Most likely this error occurs since form digest has been expired on the page.

    In that case you could acquire a new form digest value by making a POST request to /_api/contextinfo endpoint.

    Example

    function getFormDigest(webUrl) {
        return $.ajax({
            url: webUrl + "/_api/contextinfo",
            method: "POST",
            headers: { "Accept": "application/json; odata=verbose" }
        });
    }
    
    
    function createListItem(webUrl, listName, itemProperties) {
        return getFormDigest(webUrl).then(function (data) {
    
            return $.ajax({
                url: webUrl + "/_api/web/lists/getbytitle('" + listName + "')/items",
                type: "POST",
                processData: false,
                contentType: "application/json;odata=verbose",
                data: JSON.stringify(itemProperties),
                headers: {
                    "Accept": "application/json;odata=verbose",
                    "X-RequestDigest": data.d.GetContextWebInformation.FormDigestValue
                }
            });
        });
    }
    

    Usage

    //Create a Task item
    var taskProperties = {
        '__metadata': { 'type': 'SP.Data.WorkflowTasksItem' },
        'Title': 'Order approval'
    };
    
    createListItem(_spPageContextInfo.webAbsoluteUrl, 'Workflow Tasks', taskProperties)
    .done(function (data) {
        console.log('Task has been created successfully');
    })
    .fail(function (error) {
        console.log(JSON.stringify(error));
    });
    

提交回复
热议问题