dkeyboo
dkeyboo

Reputation: 15

How do I export a post request object in express Nodejs to another module

This code is returning a data object containing a user's form input exactly as I expect. I have used a variable contactFormInfo to contain that object and when I console.log(contactFormInfo) I get the object commented at the bottom of my code. My problem is how do I export this object into another module, mailer.js where I want to extract the information to use to send an email. As a newbie, I am stuck and any any help is highly appreciated.

const express = require('express');
const app = express();

// register view engine
app.set('view engine', 'ejs');

//Http listening app
app.listen(5000, ()=> console.log('Server is listenong on port 5000'));

//Middleware and static files
app.use(express.static('public'));

//Render Home Page
app.get('/', (req, res) => { res.render('index')});

app.use(express.urlencoded({ extended: true }));

//Receiving submit-form data through post request
app.post('/', (req, res)=> { let contactFormInfo = req.body;
  res.redirect('/');
  res.end();
  console.log(contactFormInfo);
});

//OUTPUT WHEN I console.log(contactFormInfo);
/*
{
  name: 'John Doe',
  email: '[email protected]',
  subject: 'Brand development',
  mobile: '0722200000',
  message: 'Please call or email'
};
*/

Upvotes: 0

Views: 994

Answers (2)

Jatin Mehrotra
Jatin Mehrotra

Reputation: 11513

You can use this approach :-

  1. Create an Email function in a separate file and export it to your app.js.

Note here I am using sendgrid API and ES6 import/export syntax.You can use your own api for sending API and normal import and export syntax.

 import sgMail from '@sendgrid/mail'
    
    
    sgMail.setApiKey(process.env.SENDGRID_API_KEY)
    
    const sendWelcomeEmail = (userEmail, nameOfUser) => {
    
      sgMail.send({
        to: userEmail,
        from: '[email protected]',
        subject: 'Welcome to Task Manager Application',
        text: `Hi There!!! How are you ${nameOfUser}?.`
        //html: '<strong>and easy to do anywhere, even with Node.js</strong>',
      });
    }
export {
  sendWelcomeEmail,
};
  1. import it in your app.js.

    import sendWelcomeEmail from 'path/to/email/function/module'

  2. Then inside app.js

Change your router like this

app.post('/', (req, res)=> { let contactFormInfo = req.body;
  res.redirect('/');
  res.end();
  sendWelcomeEmail(contactFormInfo.name,contactFormInfo.email) //pass any  properties you want to use in your mail. 
  console.log(contactFormInfo);
});

Upvotes: 0

r7r
r7r

Reputation: 1525

You will need to create a function with the logic of sending emails based on parameters it receives and import this function where your route logic is present.

and invoke the function in your mailer.js from the route with your contactFormInfo variable.

Upvotes: 1

Related Questions