0

From a SP Online SPFx Web Part (No Javascript Framework), I've been trying to do a GET request to an API that expects some headers and nothing works.

If use Postman, with the same URL and Headers it does work.

first attempt :

    var _headers = {
      'Content-Type': "text/plain",
      'Authorization': "TOKENVALUE",
      'X-Requested-With': "HREngagement",
    };

    const myOptions: ISPHttpClientOptions = {
      headers: new Headers(_headers),
      credentials: 'same-origin',
      method: 'GET',
      mode: 'no-cors',
      redirect: 'follow'
    };

    this.context.spHttpClient.get(_url, SPHttpClient.configurations.v1, myOptions)
    .then((response: SPHttpClientResponse) => {
    console.log('OK!!!!');
      console.log(response.text);
      console.log('OK!!!!');
      return response;
    });

Error:

net::ERR_ABORTED 401 (Unauthorized)

OK!!!!

ƒ () { return this.nativeResponse.text(); }

OK!!!!

Second attempt :

return axios({
  method: 'get',
  url: _url ,
  headers: {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, PUT, POST, DELETE, OPTIONS',
  'Content-Type': "text/plain",
  'Authorization': "TOKENVALUE",
  'X-Requested-With': "HREngagement",

  },
  }).then(function(response){
  return response.data;
});

Nothing works for me, these are the errors I've been getting:

Error:

Access to XMLHttpRequest at 'url' from origin 'https://localhost:4321' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Apparently consuming an external API from a SPFx Web Part it’s harder that one would imagine!

Is there any sample code for doing this?

1 Answer 1

0

Here is the official guidance about how to consume external API:

You can have a try, if it works then the error may come from the external API.

BR

2
  • I still get the problem is related to CORS: has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. Commented May 20, 2020 at 3:48
  • Have you tried it with another url? Do all request get the same result? Below is a sample you may have a look: c-sharpcorner.com/blogs/… Commented May 20, 2020 at 6:33

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.