问题
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