在SharePoint Framework中,有一个对象SPHttpClient,这个对象继承了HttpClient对象,可以使用这个对象方便地调用SharePoint REST API。
在使用这个对象之前,需要导入这个对象:
import { SPHttpClient, SPHttpClientResponse, SPHttpClientConfiguration } from '@microsoft/sp-http';
在SharePoint Framework web part的上下文中,可以直接得到这个对象:
this.context.spHttpClient
这个对象提供了get,post方法方便地获取和更新数据。
先看一下如何使用get方法获取“MyTestList"列表中的items。针对get方法,SPHttpClient对象会默认设置请求的header,所以这里不需要做任何header的设置。
this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/lists/GetByTitle('TestList')/items`,
SPHttpClient.configurations.v1)
.then((response: SPHttpClientResponse) => {
response.json().then((responseJSON: any) => {
console.log(responseJSON);
});
});
再看一下如何使用post方法更新一个id为1的item的Title字段值,这里还是需要设置正确的header,但是不需要设置令牌digist:
const data:ISPHttpClientOptions = {
headers: {
'Accept': 'application/json; odata=verbose',
'content-type': 'application/json; odata=verbose',
'X-HTTP-Method': 'MERGE',
'IF-MATCH':'*',
'OData-Version': '' },
body: JSON.stringify({
'__metadata': {
'type': 'SP.Data.MyTestListListItem'
},
'Title': `new title 1`
}),
}
this.context.spHttpClient.post(`${this.context.pageContext.web.absoluteUrl}/_api/lists/GetByTitle('MyTestList')/items(1)`,
SPHttpClient.configurations.v1, data)
.then((response: SPHttpClientResponse) => {
console.log(response);
}).catch(err => console.log(err));
注意要正确指定headers,如果没有指定header,会报如下错误:
The parameter __metadata does not exist in method GetById
或者:
The request ETag value does not match the object's ETag value...
如果没有指定’OData-Version',则会报错:
Parsing JSON Light feeds or entries in requests without entity set is not supported.