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

7
  • This SP.SE question might help you.
    – Naveen
    Jul 20, 2020 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, 2020 at 4:48
  • Did your issue fixed? Jul 24, 2020 at 6:41
  • @UtkarshDubey not yet. Do you have any solution ?
    – Ravi
    Jul 24, 2020 at 7:55
  • Try it on SharePoint web part page, instead of localhost. Jul 24, 2020 at 7:59

2 Answers 2

0

This is my code to make POST request to external API. External API must be configured to accept CORS requests.

public externalAPIpost (): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            const body: string = JSON.stringify({
                'body': YOURBODY
            });
            const httpClientOptions: IHttpClientOptions = {
                headers: {
                    'Content-Type': 'application/json; charset=utf-8',
                    'Access-Control-Allow-Origin': YOUR ORIGIN,
                    'Access-Control-Allow-Method': 'POST',
                    'Access-Control-Allow-Headers': 'Authorization',
                    'Origin': YOUR ORIGIN,
                    'Authorization': `Bearer ${my_access_token}`
                },
                method: 'POST',
                body: body
            };
            const endpoint: string = ENDPOINT URL;

            this.HttpClient.post(endpoint, HttpClient.configurations.v1, httpClientOptions)
                .then((response: HttpClientResponse) => {
                    if (response.ok) {
                        return response;
                    } else {
                        reject(this.getErrorMessage(response));
                    }
                })
                .then((respData) => {
                    resolve(respData);
                })
                .catch((error) => {
                    reject(this.getErrorMessage(error));
                });
        });
    }
private getErrorMessage(error: any): string {
        console.log (error);
        const errorMessage: string = error.errorMessage ? error.errorMessage : error;
        return errorMessage;
    }
0

Try Replace mode with no-cors,

const httpClientOptions: IHttpClientOptions = {
      body: body,
      headers: requestHeaders,
      mode: 'no-cors'
    };

Your Answer

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

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