[FIXED] axios not sending request body in nodejs

Issue

I’m trying to send a POST request using axios from NodeJS, but the body/data of the request is not sent.

I am using axios and NodeJS on the back end, and this is my NodeJS script which sends the request:

const axios = require("axios").default;

axios.post("my url goes here/email.php", {
   emailto: "receiver email",
    toname: "name",
    emailfrom: "sender email",
    fromname: "name",
    subject: "subject",
    messagebody: "hello world"
});

When the receiving server tries to read the data in the request (eg by declaring $subject = $_POST[subject]; in PHP), the parameters of the request are null – so $_POST[subject] returns null.

However, when I send the same request using not axios but jQuery (on the front end), it works perfectly in that the receiving server can now read the data of the POST request (so $_POST[subject] this time returns "subject"):

$.ajax("https://my url goes here/email.php", {
  method: "POST",
  cache: false,
  data: {
        emailto: "receiver's email",
        toname: "name",
        emailfrom: "sender email",
        fromname: "name",
        subject: "subject",
        messagebody: "hello world"
    }
})

When I run the second snippet, on the PHP-server $_POST[subject] returns "subject", but when I run the first snippet in NodeJS, $_POST[subject] returns null. Why is axios not sending my request body?

Solution

Look at the documentation for axios:

By default, axios serializes JavaScript objects to JSON

So you are POSTing JSON to the server.

PHP doesn’t support JSON when it comes to populating $_POST.

You need to POST a format that it supports, such as URL Encoded Form Data or Multipart Form Data.

(Your jQuery example is using URL Encoded Form Data).

To send data in the application/x-www-form-urlencoded format instead,
you can use the URLSearchParams API, which is supported in the vast
majority of browsers, and Node starting with v10 (released in 2018).

const params = new URLSearchParams({ foo: 'bar' });
params.append('extraparam', 'value');
axios.post('/foo', params);

Answered By – Quentin

Answer Checked By – Mildred Charles (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published