You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SPFX开发新闻展示webpart时CAML查询缺少_LikeCount与_CommentCount字段

SPFX查询Site Pages库无法获取_LikeCount、_CommentCount字段解决方案

排查&解决步骤

  • 第一步:确认页面库点赞/评论功能已开启
    进入目标站点的「站点内容」-找到「Site Pages」库-点击库设置-进入「评分设置」,确认已开启「允许对此列表中的项目进行点赞」,同时确认页面评论功能未被管理员全局禁用。未开启功能的情况下这两个字段不会在库中生成,自然无法查询到。
  • 第二步:修正请求方式与参数逻辑
    POST调用/_api/web/lists/GetByTitle('Site Pages')/GetItems端点时,URL后拼接的$select/$expand参数不生效,该端点仅识别CAML语句中的配置,你之前添加的查询参数无效。
  • 第三步:注意隐藏字段的返回名称
    使用odata 3.0版本头请求时,这两个隐藏字段的返回键名会增加OData_前缀,实际为OData__CommentCount、OData__LikeCount(两个下划线),直接读取_CommentCount会返回undefined,建议打印返回的单个项对象确认实际键名。
    如果切换为odata 4.0头(设置Accept: application/json;odata=nometadata),返回字段名会和内部名一致,直接使用_CommentCount、_LikeCount即可读取。
  • 第四步:优先选用GET请求实现需求
    对于简单的筛选排序场景,GET请求列表项端点比CAML POST更易用,支持直接通过URL参数指定字段、筛选规则、排序规则,示例代码如下:
props.topCount = props.topCount === undefined ? 5 : props.topCount;

const fetchData = async () => {
  let currentWebUrl  = props.sites === undefined ? props.origSiteURL : props.sites[0].url;
  // 构造GET请求URL,直接包含筛选、排序、字段选择逻辑
  const requestUrl = `${currentWebUrl}/_api/web/lists/GetByTitle('Site Pages')/items?$select=createdDateTime,BannerImageUrl,PromotedState,FileLeafRef,AuthorLookupId,Modified,_CommentCount,_LikeCount,Title,Description,LinkTitle&$filter=PromotedState eq 2&$orderby=_CommentCount desc&$top=${props.topCount}`;
  
  const options: ISPHttpClientOptions = {
    headers: {'Accept': 'application/json;odata=nometadata'}
  };
  
  const response = await props.spHttpClient.get(requestUrl, SPHttpClient.configurations.v1, options);
  if (response.ok) {
    const responseJSON = await response.json();
    if (responseJSON?.value) {
      settop_news_like(responseJSON.value);
      console.log(responseJSON.value);
    }
  }
};
  • 第五步:必须使用CAML POST的修正方案
    如果你需要继续使用CAML查询,需要将ViewFields正确嵌套到View节点下Query节点之前,示例CAML结构如下:
<View>
  <ViewFields>
    <FieldRef Name="_CommentCount" />
    <FieldRef Name="_LikeCount" />
    <FieldRef Name="PromotedState" />
    <!-- 其余需要返回的字段都在此处添加 -->
  </ViewFields>
  <Query>
    <OrderBy>
      <FieldRef Name="_CommentCount" Ascending="False" />
    </OrderBy>
    <Where>
      <Eq>
        <FieldRef Name="PromotedState" />
        <Value Type="Number">2</Value>
      </Eq>
    </Where>
  </Query>
  <RowLimit>${props.topCount}</RowLimit>
</View>

取值时使用item.OData__CommentCount、item.OData__LikeCount即可。

内容的提问来源于stack exchange,提问作者BizApps

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 19:54:01