3

I am trying to call the dummy API from SPFX, but I am getting an error, Failed to fetch,

  this.context.httpClient
  .get("http://dummy.restapiexample.com/api/v1/employees", HttpClient.configurations.v1)
  .then((res: HttpClientResponse): Promise<any> => {
    alert("");
    return res.json();
  })
  .then((data: any): void => {
    alert("");
    // Process your data here
  }, (err: any): void => {
    // Handle error here
  });

How can I fix this problem?

  • Where are you calling this? on SharePoint workbench or Local workbench? – Ganesh Sanap Jul 12 at 5:32
  • on sharepoint workbench – KumarV Jul 12 at 5:32
  • Your SharePoint site must be loaded over https and you are calling insecure http request. So the request will get blocked on SharePoint workbench. Instead you can try calling GET call on any of your SharePoint list like siteUrl/_api/web/lists/getbytitle('ListName')/items. – Ganesh Sanap Jul 12 at 5:37
  • its working for sharepoint list, also it works for https secured api's...Is there any way to load http request? – KumarV Jul 12 at 5:43
  • I guess you can call it using jQuery ajax or something. let me check and get back to you. – Ganesh Sanap Jul 12 at 5:45
3

Your SharePoint site must be loaded over https and you are calling insecure http request.

So the request will get blocked on SharePoint workbench.

Instead you can try calling GET call on any of your SharePoint list like:

siteUrl/_api/web/lists/getbytitle('ListName')/items

Or try any other dummy REST API over https, like:

https://jsonplaceholder.typicode.com/todos/1
3

As Ganesh mentioned, mixed content is not allowed. The content needs to be loaded over https. Having said that, you can use Cors Anywhere , a NodeJS proxy which adds CORS headers to the proxied request.

Wouldnt recommed using it for production, but if you just want to test some stuff or do some PoC work, you can see its implementation using https://cors-anywhere.herokuapp.com/ in SPFx as below:

const httpClientOptions: IHttpClientOptions = {
      headers: new Headers(),
      method: "GET",
      mode: "cors"
};

this.context.httpClient
  .get("https://cors-anywhere.herokuapp.com/http://dummy.restapiexample.com/api/v1/employees", HttpClient.configurations.v1,httpClientOptions)
  .then((res: HttpClientResponse): Promise<any> =>         
    return res.json();
  })
  .then((data: any): void => {
    console.log(data);
    // process your data here
  }, (err: any): void => {
    // handle error here
    console.log(err);
  });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.