Posting Data on Mailchimp Server and redirecting based on success rate of Post Data

 const express = require("express");

const https = require('https');
const mailchimp = require("@mailchimp/mailchimp_marketing");

// MailChimp API key
mailchimp.setConfig({
  apiKey: "3574780b3b1a31ae322ec0c4e9c08729-us5",
  server: "us5",
});

// MailChimp Audience List ID for the Newsletter
const listID = "74a14fa783";

// Start express application
const app = express();

// This line defines a static directory for local resources
app.use(express.static("public"));

// body-parser is deprecated, using this instead
app.use(express.urlencoded({extended: true}));

// When page loads, display signup.html
app.get("/"function(reqres) {
  res.sendFile(__dirname + "/signup.html");
});


// When signup.html form submitted, make request to mailchimp
app.post("/"function(reqres) {


  // create a JSON object based on collected user input
  const jsonData = {
    email_address: req.body.id,
    status: "subscribed",
    merge_fields: {
      FNAME: req.body.f1,
      LNAME: req.body.l1
    }
  };

  // async function for mailchimp to add subscriber
  const run = async function run() {

    // addListMember requires the listID of where you're putting the subscriber
    // as well the JSON object of the subscriber details
    const response = await mailchimp.lists.addListMember(listID, jsonData);
          

    // The if and else statement will redirect 
    // to the pages according to success rate
    if(response.id !== ""){
      res.sendFile(__dirname+"/success.html")
    }else{
      res.sendFile(__dirname+"/failure.html")
    }

    // get hold of the response
    console.log(response);


  };

  // run the async function
  run();

});

app.listen(3000function() {
  console.log("Server is running on port 3000.");
});

Comments

Popular posts from this blog

To read data from database using mongo driver

To do list (without styling and css)

Template, layout and scope