0

I have the following code

 this.context.spHttpClient.get(
    `${this.absoluteUrl}/?$select=Title&`,
    this.config, {
        headers:this.getHeaders,
    })
  .then((response: SPHttpClientResponse) => {
    if (response.ok) {
      response.json().then((results) => { ... 

Where I'm trying to find all list names of my Site, but I'm getting the following error

sp-webpart-workbench-assembly_es-es_3ccc282fed5f46c40407a659977d1250.js:1078 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 2

My header is the following

private getHeaders = { 
"Method": "GET",
"Accept": "application/json;odata=verbose",
"odata-version": "",
};

and if I check network request header is sending the header. I've also checked the result via web and it is returning everything on XML

I'm clueless any idea why is Sharepoint returning xml instead of json?

2 Answers 2

3

Try something like this:

return this.context.spHttpClient.get(`${this.context.pageContext.web.absoluteUrl}/_api/web/lists?$select=Title`,
      SPHttpClient.configurations.v1,
      {
        headers: {
          'Accept': 'application/json;odata=verbose',
          'odata-version': ''
        }
      });
  })
  .then((response: SPHttpClientResponse): Promise<IListItem> => {
    return response.json();
  });

Here are some reference codes on how to use spHttpClient with SharePoint: GitHub reference.

2
  • It works, thanks!, what is the difference between using headers like that, or how I did? the code seems almost the same but mine didn't work Commented May 13, 2019 at 7:42
  • I did both, but my upvotes doesn't count yet because I don't have that privilege, sorry! Commented May 13, 2019 at 7:45
0

Looks like you are using it wrong.

It needs to be as below:

1) Add the below import statement:

import { SPHttpClient, ISPHttpClientOptions , SPHttpClientResponse} from '@microsoft/sp-http';

2) After that you can use the spHttpClient as below:

var httpClientOptions : ISPHttpClientOptions = {};

httpClientOptions.headers = {
    'Accept': 'application/json;odata=verbose',
    'odata-version': ''
};

this.context.spHttpClient.get(`${this.absoluteUrl}?$select=Title`,
SPHttpClient.configurations.v1,
httpClientOptions).then((response: SPHttpClientResponse) => {
  if (response.ok) {
    response.json().then((results) => {
      console.log(results);
    })
  }
});
1
  • Tested this and it didn't work, I have the same poroblem because httpClientOptions.Headers are the same Headers I were trying to use and it still returns XML. Commented May 13, 2019 at 7:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.