wp_remote_post sends empty body

I made an api with nodejs and i'm trying to make some calls to it throught wordpress, all the requests works correctly but when i add a request body it is sent empty, i tried to search what was the problem but i found nothing that worked.

I mean if i send this request

$body = [
    'name'  = 'Pixelbart',
    'email' = '[email protected]',
    password = Pass#your!word
];
 
$body = json_encode( $body, TRUE );

echo $body; // here the body is correctly populated

$res = wp_remote_post(http://localhost:3000/users,
  array( 
    'headers' = array( 
      'Origin' = http://localhost
    ),
    'body' = $body,
    'method'      = 'POST',
    'data_format' = 'body'
  )
);

on the api side if i try to read the request body it is an empty JSON. As i thought that was an api problem i tried to send the request with other tools but if i use postman for send the reqeust in the same way it correctly works. Am i missing something? I tried also to remove all the plugins and all the custom imports for have a clear enviroment but the same error happens

[ Also ajax requesto from javascript fails if sent from the active wordpress theme ]

Topic wp-remote-request Wordpress

Category Web


The following code worked source. The 'Content-Type' => 'application/json' header was missing causing the problem

$url = 'myAPIURL HERE';
$username = 'apiuser';
$password = 'passwd';
$headers = array( 
     'Authorization' => 'Basic ' . base64_encode( "$username:$password" ), 
     'Content-Type' => 'application/json' 
);
$fields = array(
    'body' => json_encode(
        array(
         'email'     => '[email protected]',
         'name'      => 'Pixelbart',
         'password' => 'Pass#your!word'
        )
    ),
    'headers'     => $headers,
    'method'      => 'POST',
    'data_format' => 'body'
);

$response = wp_remote_post($url,$fields);

if ( is_wp_error( $response ) ) {
     $error_message = $response->get_error_message();
     echo "Something went wrong: $error_message";
} else {
     echo 'Response:<pre>';
     print_r( $response );
     echo '</pre>';
}

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.