1

I need to fetch few details from the 3rd party API so I am making a POST request (required by the API) to that API using HttpClient But every time I am getting the below error.

Access to fetch at 'https://3rd-party API url' from origin 'https://localhost:4321' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status. and then it simply returns invalid token error.

Below is my code :

import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http';

  private getDetails(jwt_token: string): Promise<HttpClientResponse> {

    let postURL = "https://3rd-party API url";

    const bodyJson = JSON.stringify({
        //json to fetch
    });

    let bearer = "Bearer " + jwt_token;

    const requestHeaders: Headers = new Headers();
    requestHeaders.append('Authorization', bearer);
    requestHeaders.append('Content-Type', 'application/json');  

    const httpClientOptions: IHttpClientOptions = {
      body: bodyJson,
      headers: requestHeaders,
      mode: 'cors',
      // method: 'POST',
      // redirect: 'follow'
    };

    return this.props.HttpClient.post(
      postURL,
      HttpClient.configurations.v1,
      httpClientOptions)
      .then((response): Promise<HttpClientResponse> => {
        //Here it throws error
        return response.json();
      })
      .then(jsonResponse => {
        debugger;
        return jsonResponse;
      }) as Promise<any>;
  }

  componentDidMount() {
    this.getDetails(accessToken));
  }

I have tried to set the below extra headers apart from the mandatory Content-Type & Authorization headers (required by the API):

requestHeaders.append('Access-Control-Allow-Origin', '*');
requestHeaders.append("Access-Control-Allow-Methods", "POST");
requestHeaders.append("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Authorization, Access-Control-Allow-Methods");

Same error occurs when I run this from the hosted workbench.

It just works fine with the Postman and returns result without even mentioning these headers. Is there anything extra do I need to add to fetch the results from third party API ? Thanks

  • This SP.SE question might help you. – Naveen Jul 20 at 14:27
  • Thanks for the link @Naveen. Already have been through this answer, It did not provide any solution in my case. – Ravi Jul 21 at 4:48
  • Did your issue fixed? – Utkarsh Dubey Jul 24 at 6:41
  • @UtkarshDubey not yet. Do you have any solution ? – Ravi Jul 24 at 7:55
  • Try it on SharePoint web part page, instead of localhost. – Utkarsh Dubey Jul 24 at 7:59

Your Answer

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

Browse other questions tagged or ask your own question.