0

I made a post request using Axios in ReactJS to my node.js server. What it does is send automated emails.

Now I'm trying to pass data from the Axios call to my node.js server, for example I'm passing { test: "abc" } here, but in my node.js server, req.test will be undefined.

Did I make a mistake somewhere?

ReactJS axios POST call

axios
  .post("http://localhost:3000/send", {
    data: {
      test: "abc",
    },
  })
  .then((response) => {
    console.log(response);
  });

Node.js application (listening on port 3000)

app.post("/send", (req, res) => {
    console.log(req.test); // undefined
    const output = `<h3>Message</h3>`;

    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport(smtpTransport({
        name: "sj9",
        host: "mail.sj9.co",
        port: 465,
        secure: true, // true for 465, false for other ports
        auth: {
          user: "test@sj9.co", // generated ethereal user
          pass: "jailbreak", // generated ethereal password
        },
        tls: {
          rejectUnauthorized: false,
        },
    }));

    // setup email data with unicode symbols
    let mailOptions = {
        from: '"My Name" <test@sj9.co>', // sender address
        to: "my-email@gmail.com", // list of receivers
        subject: "Node Contact Request", // Subject line
        text: "Hello world?", // plain text body
        html: output, // html body
    };

    // send mail with defined transport object
    transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          return console.log(error);
        }
        console.log("Message sent: %s", info.messageId);
        console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info));
    });
});
SJ19
  • 1,933
  • 6
  • 35
  • 68
  • when you post something, the parameters should be accessed using `body` prop of the request. In order to do that, you should have `bodyparser` package installed and imported in your app. But don't worry! assuming that you are using express; Newer versions of express have `bodyparser` built-in, make sure that you have `app.use(express.json()); app.use(express.urlencoded({ extended: false }));` in your root where you initialise your app. Then try accessing your properties using `req.body.test` – rand0m Oct 11 '20 at 18:06
  • @rand0m That's it! Thank you! If you want to make an answer I'll approve it. – SJ19 Oct 11 '20 at 18:48
  • that's all right mate, life's not all about points. I'm glad that you got your answer :) – rand0m Oct 11 '20 at 19:42
  • @rand0m Well it isn't all about points (that's just your reward :)), it's also about showing the right answer for other people and resolving the question. – SJ19 Oct 12 '20 at 13:50

0 Answers0