POST request: handle parameters and send them via email

Hello!
I set up a basic server which has to be a Webhook endpoint with express, that needs to do these things:
1 - receive an x-www-form-urlencoded post request
2 - check if a certain parameter has a certain value
3 - if 2 is true, then it needs to send all the parameters values to a specific mail address.

I’m a newbie in js and programming in general, is there any resource you could point me to which explains how to do something like that?
N 2 could be dealt with using url searchparams or maybe req.params/req.query?
Should I then turn the parameters into an object in order to send it somewhere else?

Thank you and sorry if I didn’t bring much to the table for start!
Andrea

Hello.

  1. First of all, you need to parse the request body. You can use middleware for this (Using Express middleware). Since you will get x-www-form-urlencoded, you will need the bodyParser.urlencoded() middleware (Express body-parser middleware). With the parsed body in req.body you can check the parameters.
  2. Then choose a library for sending emails and read the docs to understand how to use it. See for example https://nodemailer.com/

That’s all!

Thank you very much!!
I think I got it now, at least with the ethereal test mail it seems to be working.
I used the express.urlencoded since I read body parser is deprecated and now urlencoded middleware is part of express.
I was able now to access the parameters and send the mail based on a condition.

This is the code example if anyone will be interested in the future. Also if you can check if the code is right, or something is redundant or not needed.

app.post("/", (req, res) => { const gruppo = req.body.gruppo; const nome = req.body.nome; const telefono = req.body.telefono; let message = { from: "example@ethereal.email", to: "example@mail", subject: "Message title", text: `Info. Nome: ${nome}, telefono: ${telefono}`, }; if (gruppo === '122') { transporter.sendMail(message); } res.send('post request received'); });

I have one more question: the thing I am trying to achieve here is that when “gruppo === x” send email to “John”, when “gruppo === y” send email to “George” et cetera, up to 10-20 conditions like that.
What would be best:

  • manage it through switches or if else
  • manage it through different routes (which I can do partially)
  • manage it through different servers

I hope I was clear

Hi!

The simplest way is to use object with gruppo => recipient mapping:

const gruppoToRecipient = {
  x: 'John',
  y: 'George',
};

const recipient = gruppoToRecipient[gruppo] || 'Default recipient';
1 Like

Hello!
If I understand this correctly, doing so I can delete the if statement and put the recipient variable as value of to: instead of the email, correct?
Thanks a lot!

Hi!

Yes, but consider the case where gruppo is not in the gruppoToRecipient object and from gruppoToRecipient[gruppo] you will get undefined.

1 Like