I've very simple setup for testing my PHP / JS interface. But the POST parameters are not set by the fetch request.
Client (JS):
function request(url, data, options) {
const fetchOptions = options;
// Add data to options
fetchOptions['body'] = JSON.stringify(data);
return fetch(url, fetchOptions);
}
function getUsers() {
const url = 'http://127.0.0.1:8200/api.php';
const data = { 'api': 'GET_USERS' };
const options = {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
};
request(url, data, options)
.then(response => response.json())
.then(data => console.log(data));
}
All I want to test is to send the POST parameter api
with the value GET_USERS
and recieve the server response (json) that checks if the POST parameter was set properly.
Server(php):
$response = array();
$meta = array();
if (isset($_POST['api'])) {
$meta['api'] = $_POST['api'];
} else {
$meta['api'] = null;
}
$response['meta'] = $meta;
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Authorization, X-Requested-With");
// Send data to client
echo json_encode($response, JSON_UNESCAPED_UNICODE);
But the POST paramter api
is not set - so I always recieve `{api: null;}' from the server. I already tried the following things:
- Use
body: data
instead ofbody: JSON.stringify(data)
- Initialize the
data
asnew FormData()
and add theapi
key-value pair bydata.append('api', 'GET_USERS')
Setup:
- PHP: 8.1.2
- Webserver: Apache 2.4.52