0

No error appears (Would be good if appeared), and i've passed the whole day trying to make this code work. It's my first time with fetch using POST. The thing is: the backend can't find any POST. I will explain better after showing my scripts.

This is my front-end:

const corpo = {
    email: 'vila07@hotmail.com',
    password:'123',
}   
let url = "http://localhost/beauty/src/backend/login.php";
const options ={
    method: 'POST',
    mode: 'cors',
    header:{
        'Content-Type':'application/json',
        'Accept':'application/json',
    },
    body: JSON.stringify(corpo),
}

fetch(url,options)
.then((r)=>r.json())
.then((r)=>{
console.log(r);
});

I should be able to get email and password in my backend, but when I use:

if(!isset($_POST['email']) || !isset($_POST['password'])){
}

The code is triggered, because there is no email and no password in POST.

See my backend. I don't understand much about headers, wonder if the problem is in there. I used a standard one.

<?php
if (isset($_SERVER['HTTP_ORIGIN'])) { 
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS"); 
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}

$array = array();
if(isset($_POST['email']) || isset($_POST['password'])){
    $array = array(
        'email'=>'aa',
        'password'=>'bb'
    );
    echo json_encode($array);
}
else
{
    $array = array(
        'email'=>'No post found',
        'password'=>'No post found'
    );
    echo json_encode($array);   
}
?>

It is returning me this part of the code:

$array = array(
        'email'=>'No post found',
        'password'=>'No post found'
    );
  • Just tried without headers, the problem persists! – Vi almeida Aug 17 '22 at 00:15
  • PHP doesn't parse JSON into `$_POST`. See the linked question for how to parse JSON body. – Barmar Aug 17 '22 at 00:15
  • Put this in your PHP file to see the full POST data sent: $post = file_get_contents('php://input'); – Schwarz Software Aug 17 '22 at 00:20
  • Thank you guys, it really helped me. So I could take the data this way: $post = file_get_contents('php://input'); $post = json_decode($post); $email = $post->{'email'}; Is there a problem taking the data this way? I Appreciate your help :D – Vi almeida Aug 17 '22 at 02:02

0 Answers0