This is a well known problem with CORS policy. To overcome this problem you need access rights to the server side API. In particular, you have to add a line in the header of php or another server endpoint:
<?php
header('Access-Control-Allow-Origin: *');
//or
header('Access-Control-Allow-Origin: http://example.com');
// Reading JSON POST using PHP
$json = file_get_contents('php://input');
$jsonObj = json_decode($json);
// Use $jsonObj
print_r($jsonObj->message);
...
// End php
?>
Also, make sure NOT to have in the header of your server endpoint:
header("Access-Control-Allow-Credentials" : true);
Model of working fetch code with POST request is:
const data = {
optPost: 'myAPI',
message: 'We make a research of fetch'
};
const endpoint = 'http://example.com/php/phpGetPost.php';
fetch(endpoint, {
method: 'POST',
body: JSON.stringify(data)
})
.then((resp) => resp.json())
.then(function(response) {
console.info('fetch()', response);
return response;
});
'mode': 'no-cors'
. Among the effects of specifying that are, it tells the browser to treat the response as opaque —and it’s named that way because it means your JavaScript code can’t see it. At all. If the reason you’re specifying'mode': 'no-cors'
is that you otherwise get an error message about No Access-Control-Allow-Origin, then you need to realize that'mode': 'no-cors'
isn’t a fix for that – sideshowbarker