SPFX Sharepoint搜索其余api / _api / search / postquery响应无法转换为.json

问题描述

我使用Rest api向SharePoint搜索执行发布请求,但确实得到了响应代码200,但无法将响应转换为json

 public static SPSearch(searchObj: ISearchRequest,context: any): Promise<ISPSearchResult> {

        var results: IResultProperty[] = null
        const spOpts: ISPHttpClientOptions = searchObj as ISPHttpClientOptions
        let config: SPHttpClientConfiguration = new SPHttpClientConfiguration({
            defaultODataVersion: ODataVersion.v3
        });
        let requestUrl = context.pageContext.web.absoluteUrl + constants.spSearchPostUrl; //_api/search/postquery

        return this._getdigest(context)
            .then((digrestJson: any) => {
                console.log(digrestJson);
                const digest = digrestJson.FormDigestValue;
                const headers = {
                    'X-RequestDigest': digest,"content-type": "application/json;odata=verbose",};

                return context.spHttpClient.post(requestUrl,config,{ headers,"body": JSON.stringify(searchObj) })
                    .then((searchResults: SPHttpClientResponse) => {
                        return searchResults.json() //SyntaxError: Unexpected token < in JSON at position 0
                    }).catch((err: SPHttpClientResponse) => {
                        return err
                    });
            });

    }

解决方法

我的测试代码供您参考:

   import { Version } from '@microsoft/sp-core-library';
    import {
      IPropertyPaneConfiguration,PropertyPaneTextField
    } from '@microsoft/sp-property-pane';
    import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
    import { escape } from '@microsoft/sp-lodash-subset';
    
    import styles from './SpfxCallRestDemoWebPart.module.scss';
    import * as strings from 'SpfxCallRestDemoWebPartStrings';
    import { HttpClient,IHttpClientOptions,HttpClientResponse,ISPHttpClientOptions,SPHttpClient,IDigestCache,DigestCache } from '@microsoft/sp-http';
    export interface ISpfxCallRestDemoWebPartProps {
      description: string;
    }
    
    export default class SpfxCallRestDemoWebPart extends BaseClientSideWebPart<ISpfxCallRestDemoWebPartProps> {
      protected onInit(): Promise<void> {
        return new Promise<void>((resolve: () => void,reject: (error: any) => void): void => {
          const digestCache: IDigestCache = this.context.serviceScope.consume(DigestCache.serviceKey);
          digestCache.fetchDigest(this.context.pageContext.web.serverRelativeUrl).then((digest: string): void => {
            this.callRest(digest)
            resolve();
          });
        });
      }
      public render(): void {
        this.domElement.innerHTML = `
          <div class="${ styles.spfxCallRestDemo}">
            <div class="${ styles.container}">
              <div class="${ styles.row}">
                <div class="${ styles.column}">
                  <span class="${ styles.title}">Welcome to SharePoint!</span>
                  <p class="${ styles.subTitle}">Customize SharePoint experiences using Web Parts.</p>
                  <p class="${ styles.description}">${escape(this.properties.description)}</p>
                  <a href="https://aka.ms/spfx" class="${ styles.button}">
                    <span class="${ styles.label}">Learn more</span>
                  </a>
                </div>
              </div>
            </div>
          </div>`;
        
      }
    
      protected get dataVersion(): Version {
        return Version.parse('1.0');
      }
    
      public callRest(digest) {
        const body: string = JSON.stringify({
          "request": {
            "__metadata": {
              "type": "Microsoft.Office.Server.Search.REST.SearchRequest"
            },"Querytext": "FileExtension:aspx"
          }
        });
    
        const requestHeaders: Headers = new Headers();
        requestHeaders.append('accept','application/json;odata=verbose');
        requestHeaders.append("Content-Type","application/json;odata=verbose");
        requestHeaders.append("X-RequestDigest",digest)
        const httpClientOptions: ISPHttpClientOptions = {
          body: body,headers: requestHeaders
        };
        let currentWebUrl = this.context.pageContext.web.absoluteUrl;
        let requestUrl = currentWebUrl.concat(`/_api/search/postquery`)
        
        this.context.httpClient.post(
          requestUrl,HttpClient.configurations.v1,httpClientOptions)
          .then(response=> {
            response.json().then(r=>console.log(r.d))
            return response.json()
          });
        
      }
    
      protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
        return {
          pages: [
            {
              header: {
                description: strings.PropertyPaneDescription
              },groups: [
                {
                  groupName: strings.BasicGroupName,groupFields: [
                    PropertyPaneTextField('description',{
                      label: strings.DescriptionFieldLabel
                    })
                  ]
                }
              ]
            }
          ]
        };
      }
    }

测试结果: enter image description here