Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

253
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda