Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/search/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SPFX Sharepoint search rest api/_api/search/postquery响应无法转换为.json()_Post_Search_Sharepoint Online_Spfx_Restapi - Fatal编程技术网

SPFX Sharepoint search rest api/_api/search/postquery响应无法转换为.json()

SPFX Sharepoint search rest api/_api/search/postquery响应无法转换为.json(),post,search,sharepoint-online,spfx,restapi,Post,Search,Sharepoint Online,Spfx,Restapi,我使用RESTAPI执行对SharePoint搜索的post请求,得到的响应代码为200,但无法将响应转换为json public static SPSearch(searchObj: ISearchRequest, context: any): Promise<ISPSearchResult> { var results: IResultProperty[] = null const spOpts: ISPHttpClientOptions =

我使用RESTAPI执行对SharePoint搜索的post请求,得到的响应代码为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
                    });
            });

    }

publicstaticspsearch(searchObj:ISearchRequest,context:any):承诺{
变量结果:IResultProperty[]=null
常量spOpts:ISPHttpClientOptions=searchObj作为ISPHttpClientOptions
let config:SPHttpClientConfiguration=新的SPHttpClientConfiguration({
defaultODataVersion:ODataVersion.v3
});
让requestUrl=context.pageContext.web.absoluteUrl+constants.spsearchpostrl;//\u api/search/postquery
返回此。\u getdigest(上下文)
.然后((digrestJson:any)=>{
log(digrestJson);
const digest=digrestJson.FormDigestValue;
常量头={
“X-RequestDigest”:摘要,
“内容类型”:“应用程序/json;odata=verbose”,
};
返回context.spHttpClient.post(requestUrl,config,{headers,“body”:JSON.stringify(searchObj)})
.然后((搜索结果:SPHttpClientResponse)=>{
返回searchResults.json()//语法错误:json中位置0处的意外标记<
}).catch((错误:SPHttpClientResponse)=>{
返回错误
});
});
}

我的测试代码供您参考:

   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
                    })
                  ]
                }
              ]
            }
          ]
        };
      }
    }
从'@microsoft/sp core library'导入{Version};
进口{
IPropertyPaneConfiguration,
PropertyPaneTextField
}从“@microsoft/sp属性窗格”;
从'@microsoft/sp webpart base'导入{BaseClientSideWebPart};
从'@microsoft/sp lodash subset'导入{escape};
从“/SpfxCallRestDemoWebPart.module.scss”导入样式;
将*作为字符串从“SpfxCallRestDemoWebPartStrings”导入;
从“@microsoft/sp http”导入{HttpClient、IHttpClient、HttpClientResponse、ISPHttpClientOptions、SPHttpClient、IDigestCache、DigestCache};
导出接口ISpfxCallRestDemoWebPartProps{
描述:字符串;
}
导出默认类SpfxCallRestDemoWebPart扩展BaseClientSideWebPart{
受保护的onInit():承诺{
返回新承诺((解析:()=>void,拒绝:(错误:any)=>void):void=>{
const digestCache:IDigestCache=this.context.serviceScope.consume(digestCache.serviceKey);
digestCache.fetchDigest(this.context.pageContext.web.serverRelativeUrl)。然后((摘要:字符串):void=>{
这是callRest(摘要)
解决();
});
});
}
公共呈现():void{
this.doElement.innerHTML=`
欢迎使用SharePoint!

使用Web部件自定义SharePoint体验

${escape(this.properties.description)}

`; } 受保护的get-dataVersion():版本{ 返回Version.parse('1.0'); } 公众电话查询(摘要){ const body:string=JSON.stringify({ “请求”:{ “_元数据”:{ “键入”:“Microsoft.Office.Server.Search.REST.SearchRequest” }, Querytext:“文件扩展名:aspx” } }); const requestHeaders:Headers=newheaders(); append('accept','application/json;odata=verbose'); append(“内容类型”,“应用程序/json;odata=verbose”); 追加(“X-RequestDigest”,摘要) 常量httpClientOptions:ISPHttpClientOptions={ 身体:身体,, 标题:请求标题 }; 让currentWebUrl=this.context.pageContext.web.absoluteUrl; 让requestUrl=currentWebUrl.concat(`/\u api/search/postquery`) this.context.httpClient.post( 请求URL, HttpClient.configurations.v1, httpClientOptions) 。然后(响应=>{ response.json().then(r=>console.log(r.d)) 返回response.json() }); } 受保护的getPropertyPaneConfiguration():IPropertyPaneConfiguration{ 返回{ 页码:[ { 标题:{ 描述:strings.PropertyPaneDescription }, 小组:[ { groupName:strings.BasicGroupName, 组字段:[ PropertyPaneTextField('说明'{ 标签:strings.DescriptionFieldLabel }) ] } ] } ] }; } }
测试结果: