I have an Express app which has the following POST route:
//Main API route
app.post("/api/v1/forms/:formId", async (req, res) => {
//TODO: Create Mailer and email templates before finalising route.
const { _name, _email, _message } = req.body;
let newForm;
Form.findById(req.params.formId, err => {
if (err) {
res.send(err);
} else {
const newForm = new Form({
name,
email,
message,
recipient: form.recipient
});
res.send(req.body);
}
});
const mailer = new Mailer(newForm, contactFormTemplate(newForm));
try {
await mailer.send();
} catch (err) {
res.status(422).send(err);
}
});
When I make a POST request to this route, the res.send(req.body);
returns an empty object and I get the error "UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReferenceError: newForm is not defined"
I can't see why it is saying the variable newForm
is not defined. I have found that the newForm
is undefined in the Mailer line:
const mailer = new Mailer(newForm, contactFormTemplate(newForm));
I can't see why this line is not being passed the newForm variable as it is in the same app.post function scope.