I'v been trying to access various apis through SPFx and I am constantly seeing this issue. I do not know how to fix this can anyone assist or explain what I am doing wrong or missing?

This works perfectly fine with $.getJSON("https://www.mindicador.cl/api").then(console.log)

workbench.html:1 Access to fetch at 'https://www.mindicador.cl/api' 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.

My function:

  private makeRequest(): Promise<HttpClientResponse> {
        const url = `https://www.mindicador.cl/api`;

        const requestHeaders: Headers = new Headers();

        requestHeaders.append("Content-type", "application/json");
        requestHeaders.append("Accept", "application/json");
        requestHeaders.append("Access-Control-Allow-Origin", "*");

        const httpClientOptions: IHttpClientOptions = {
            headers: requestHeaders,
            method: "GET"
        };

        return this.context.httpClient
            .get(url, HttpClient.configurations.v1, httpClientOptions)
            .then(response => {
                console.log(response);
                return response.json();
            });
    }
有帮助吗?

解决方案

The difference between jquery call and the native httclient call is a method of making http asynchronous request.
jquery uses old good xhr, but httpclient uses modern fetch api. When making CORS request with fetch API sometimes browser sends preflight request to understand server CORS possibilities (which origins are accepted, which headers, etc.). Your service, https://www.mindicador.cl/api doesn't support preflight requests, that's the reason why it fails.

The good news is that it's possible to remove preflight request under certain conditions. You can read more in this answer here:

To disable the OPTIONS request, below conditions must be satisfied for ajax request: Request does not set custom HTTP headers like 'application/xml' or 'application/json' etc The request method has to be one of GET, HEAD or POST. If POST, content type should be one of application/x-www-form-urlencoded, multipart/form-data, or text/plain

Which means that you should remove all custom headers to make it work:

const url = `https://www.mindicador.cl/api`;

const httpClientOptions: IHttpClientOptions = {
    headers: new Headers(),
    method: "GET",
    mode: "cors"
};

this.context.httpClient
    .get(url, HttpClient.configurations.v1, httpClientOptions)
    .then(response => {
        console.log(response);
        return response.json();
    });  
许可以下: CC-BY-SA归因
scroll top