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?

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

| improve this answer | |
  • 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. – jose luis gonzalez clua May 20 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/… – Baker_Kong_MSFT May 20 at 6:33

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.