I am trying to do a test request from my localhost, to a dev site I have just to test out some code. I am trying to make a very simple fetch
request that simply just echos a response back in the form of json
. This is cross site request and am disabling cors. The issues is, when I try to echo a response with echo json_encode
the response says: failed to load response data: No data found for resource with given identifier
.
However, if I simply fire a regular echo 'a';
before the echo json_encode
both responses now show up in the network tab. I am using Chrome. Here some code:
fetch('https://example.com/test.php',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
mode: "no-cors",
body:JSON.stringify({
test:'1'
})
})
.then(r => r.json())
.then(function(r){
console.log(r)
})
In php I simply have, which returns nothing.
if(empty($_POST)){
$_POST = json_decode(file_get_contents("php://input"), true);
}
echo json_encode(['200'=>'Got it']);
If I do:
echo 'x';
echo json_encode(['200'=>'Got it']);
My response looks like: (which the browser detects as proper json)
x{'200':'Got it'}
Do you have any ideas? I have tried putting any/all of these in my php file:
ini_set('display_errors', 1);
header("Cache-Control: no-cache, must-revalidate");
header("Content-type: application/json");
header("Access-Control-Allow-Origin: *");
json_last_error_msg();
Any ideas? thank you.
CodePudding user response:
You can echo out either an array or an object:
$obj = new stdClass();
$obj->message = 'gotit';
$obj->code = 200;
echo json_encode($obj); // prints {"message":"gotit","code":200}
$arr = Array('200' => 'gotit');
echo json_encode($arr); // prints {"200":"gotit"}
CodePudding user response:
see if this works
<?php
$content = trim(file_get_contents("php://input"));
echo json_encode(['200'=>'Got it']);
exit();