记录一个使用pnpjs时遇到的一个问题

使用SPFx创建了一个webpart,其中使用pnpjs访问列表,在online workbench中一切正常,因为workbench的url是https://contoso.sharepoint.com/sites/testweb/_layouts/15/workbench.aspx

代码如下,这里使用sp这个全局对象,获取当前web,然后读取list数据:

sp.web.lists
  .getByTitle('TestList').items.get()
  .then(items => console.log(items))
  .catch(err => console.log(err));

但是将webpart部署到tenant租户中,然后添加到页面上的时候,发现pnpjs读取列表数据报错,出现了一个404的错误:

Uncaught (in promise) Error: Error making HttpClient request in queryable [404]

经过debug发现pnpjs调用的rest api url是错误的:

https://contoso.sharepoint.com/sites/Testweb/SitePages/_api/web/lists/getByTitle('TestList')

正常的rest api url 应该是:

https://contoso.sharepoint.com/sites/Testweb/_api/web/lists/getByTitle('TestList')

原因是直接在页面中运行pnpjs,sp对象获取的url是不正确的,此时可以通过指定url的方式构造Site或者Web对象如下:

import { Site, Web } from '@pnp/sp';

const site = new Site('网站集url');
const web = new Web('网站url');


//这里的网站集url可以在webpart的上下文对象中获取到:this.context.pageContext.site.absoluteUrl
//同样网站url:this.context.pageContext.web.absoluteUrl

所以在开发webpart的时候,应该用最小的可用对象,例如操作一个web,就构造一个web对象,而不是直接使用sp这个全局对象。

参考:

https://github.com/SharePoint/PnP-JS-Core/issues/411

https://github.com/pnp/pnpjs/issues/523

发布了189 篇原创文章 · 获赞 15 · 访问量 26万+

猜你喜欢

转载自blog.csdn.net/shrenk/article/details/93969528
今日推荐