Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

249
Views
JS/PHP: Fetch does not send POST parameter

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 of body: JSON.stringify(data)
  • Initialize the data as new FormData() and add the api key-value pair by data.append('api', 'GET_USERS')

Setup:

  • PHP: 8.1.2
  • Webserver: Apache 2.4.52
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!