0

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' => 'pixelbart@example.com',
    "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 ]

2
  • Post data should be sent in the body as an array. - developer.wordpress.org/reference/functions/wp_remote_post – Q Studio Jan 30 at 18:13
  • @QStudio actually i saw that in this way sould work also, but idk. Anyway i've already tried to send them as array but didn't work. Also ajax requesto from javascript fails if sent from the active wordpress theme – Mat.C Jan 30 at 18:17
1

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'     => 'pixelbart@example.com',
         '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>';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.