Home > Enterprise >  Optional parameters in express.js
Optional parameters in express.js

Time:07-27

I'm trying to do a email sender with all components, from, to, subject, textBody and etc..., but I don't know how to set optional parameters in express.js, I have already searched for some different stackoverflow questions but none answers to my question, see here my code:

//Here I have doubts 
app.get(`/from=:from&to=:to&subject=:subject?&textBody=:textBody?&htmlBody=:htmlBody?&cc=:cc?&bcc=:bcc?&attachments=:attachments?`, (req, res) => {

  const from = req.params.from;
  const to = req.params.to;
  const subject = req.params.subject;
  const textBody = req.params.textBody;
  const htmlBody = req.params.htmlBody;
  const cc = req.params.cc;
  const bcc = req.params.bcc;
  const attachments = req.query.attachments;

//code goes here...

})

Please help me. I will appreciate your answers

CodePudding user response:

You just need to add ? to make params optional. Update your route as this by adding ?. undefined will be value if no value supplied in associated param. For example if subject is not supplied req.params.subject will be undefined you can add your logic to have desired / default value to subject field,

app.get(
  `/api/sendemail/:from?/:to?/:subject?/:textBody?/:htmlBody?/:cc?/:bcc/:attachments?`,
  (req, res) => {
    const from = req.params.from;
    const to = req.params.to;
    const subject = req.params.subject ? req.params.subject : '';
    const textBody = req.params.textBody;
    const htmlBody = req.params.htmlBody;
    const cc = req.params.cc;
    const bcc = req.params.bcc;
    const attachments = req.query.attachments;

    //code goes here...
  }
);
  • Related