标签:get SPHttpClient SharePoint header 对象 context 交互
在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.
标签:get,SPHttpClient,SharePoint,header,对象,context,交互 来源: https://blog.csdn.net/shrenk/article/details/88766414
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。