SharePoint Asked on October 25, 2021
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
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP