1

I keep getting this error message when I am sending a fetch request from the admin side. I want to connect to that API and get some response.

Access to fetch at 'https://34557322456.execute-api.ap-southeast-1.amazonaws.com/V1/code?kdata=something' from origin 'https://mywebsite.online' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Is there a WordPress way to get it fixed?

Please help thanks

Tried these :

add_filter( 'allowed_http_origin', '__return_true' );
function add_cors_http_header(){
    header("Access-Control-Allow-Origin: *");
}
add_action('init','add_cors_http_header');

add_filter('allowed_http_origins', 'add_allowed_origins');

function add_allowed_origins($origins) {
    $origins[] = 'https://34557322456.execute-api.ap-southeast-1.amazonaws.com';
    $origins[] = 'https://34557322456.execute-api.ap-southeast-1.amazonaws.com/V1/code';
    return $origins;
}

this is the fetch request

 fetch('https://34557322456.execute-api.ap-southeast-1.amazonaws.com/V1/code?kdata=something', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          'Access-Control-Allow-Origin': '*',
        },
      }).then(response => {
        return response.json()
      })
      .then(data => console.log(data))
      .catch(error => console.log(error));

This works but not the fetch method

$response = wp_remote_get('https://34557322456.execute-api.ap-southeast-1.amazonaws.com/V1/code?kdata=something');
        //var_dump($response);
    $responseBody = wp_remote_retrieve_body( $response );
  $result = json_decode( $responseBody );
    var_dump($result);
2
  • 3
    The resource mentioned in that message refers to the one on the site you're making the request to, i.e. the subdomain/site on amazonaws.com, whereas the origin is your site, i.e. mywebsite.online. So CORS needs to be enabled on the resource, which basically means you'd need to have control over the API. Nonetheless, check out this article and hopefully you'll understand why wp_remote_get() works, what CORS is, etc - if you still have questions, then try asking on Stack Overflow.
    – Sally CJ
    Commented Jan 9, 2021 at 8:16
  • 1
    @SallyCJ Thank you I solved it. I was using a lambda function written in python it's response was not having the access-control-allow-origin.
    – user145078
    Commented Jan 9, 2021 at 8:56

0