Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

260
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda