403 forbidden and 400 bad request errors while adding and deleting items to SharePoint list using REST

空扰寡人 提交于 2019-12-11 19:23:30

问题


Hi I'm new to SharePoint development. I'm Trying to develop simple SharePoint App using SharePoint online. I have a List named 'Products' in my site collection. in my app i wrote the following code to add and delete items to that list

 function addProduct(product) {
 var executor;
 executor = new SP.RequestExecutor(appwebUrl);
 var url = appwebUrl +"/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Products')/items/?@target='" + hostwebUrl+"'";
 executor.executeAsync({
    url: url,
    method: "POST",
    body: JSON.stringify({__metadata: { type: 'SP.Data.ProductsListItem' },
        Title: product.ProductName(),
        ProductId: product.ProductId(),
        ProductName: product.ProductName(),
        Price:product.Price()
    }),
    headers: {
        "Accept": "application/json; odata=verbose",
        "content-type": "application/json;odata=verbose",
        },
    success: successProductAddHandler,
    error: errorProductAddHandler
});
}


function successProductAddHandler(data) {alert('added successfully') }
function errorProductAddHandler(data, errorCode, errorMessage) { alert('cannot perform action') }


function deleteProduct(product) {
var executor;
executor = new SP.RequestExecutor(appwebUrl);
var url=appwebUrl+"/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Products')/items('" + product.ID() + "')/?@target='" + hostwebUrl + "'";
executor.executeAsync({
    url: url,
    method: "POST",
    headers: {

        "IF-MATCH": "*",
        "X-HTTP-Method": "DELETE"
    },
    success: successProductAddHandler,
    error: errorProductAddHandler
});`

Im getting 403 error when i call addProduct, and 400 error when i call deleteProduct, im able to get the list items and display.

I tried adding X-RequestDigest": $("#__REQUESTDIGEST").val() but not worked

if i include "Accept": "application/json; odata=verbose" in request header for deleteProduct(), and when i call deleteProduct two request are going to server

1).sites/productsdev/productsapp/_api/contextinfo (getting digest value)

2)/sites/ProductsDev/ProductsApp/_api/SP.AppContextSite(@target)/web/lists/getbytitle('Products')/items(itemid)/?@target='mysitecollectionurl' (using the digest value returned by the above call for X-RequestDigest)


回答1:


Whenever you are doing any POST operation in SharePoint 2013 using REST API you have to pass below snippet in header

"X-RequestDigest": $("#__REQUESTDIGEST").val()

eg

headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() }



来源:https://stackoverflow.com/questions/17193290/403-forbidden-and-400-bad-request-errors-while-adding-and-deleting-items-to-shar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!