Closed 4 years ago.
- Questions that are too localized (such as syntax errors, code with restricted access, hacked sites, hosting or support issues) are not in scope. See how do I ask a good question?
- Your question should be specific to WordPress. Generic PHP/JS/SQL/HTML/CSS questions might be better asked at Stack Overflow or another appropriate Stack Exchange network site. Third-party plugins and themes are off-topic for this site; they are better asked about at their developers' support routes.
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 '' from origin '' 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[] = '';
$origins[] = '';
return $origins;
}
this is the fetch request
fetch('', {
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('');
//var_dump($response);
$responseBody = wp_remote_retrieve_body( $response );
$result = json_decode( $responseBody );
var_dump($result);