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?
CodePudding user response:
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);
CodePudding user response:
add a content body such as { headers: {'Content-Type': 'application/json'}
to the request but I would edit this and
const axios = require("axios");
var data = JSON.stringify({
emailto: "receiver email",
toname: "name",
emailfrom: "sender email",
fromname: "name",
subject: "subject",
messagebody: "hello world"
});
var config = {
method: 'post',
url: 'https://alpha-howl.com/database/email.php',
headers: {
'Content-Type': 'application/json'
},
data : data
};
try {
await axios(config)
} catch (ex) {
throw ex
}
Mainly to make sure you are resolving the promise that is returned by axios to make sure the request is even successful.