'How to subscribe a new member to mailchamp using node.js and express

I am trying to work with an API, specifically mail-chimp API, but the problem that I am having is:

const express=require("express");
const bodyparser=require("body-parser");
const request=require("request");
const https=require("https");
const app=express();


app.use(express.static("public"));
app.use(bodyparser.urlencoded({extended:true}));

app.get("/",function(req,res){
res.sendFile(__dirname + "/signup.html");

});

app.post("/", function(req,res){
const firstName=req.body.fName;
const lastName=req.body.lName;
const email=req.body.email;

const data={
  members: [{

    email_adress:email,
    status: "subscribed",
    merge_fields:{
      FNAME:firstName,
      LNAME:lastName,
    }
  }
  ]
}

var jsonData=JSON.stringify(data);
//"https://us18.api.mailchimp.com/3.0/list/024346747a3"
const url="https://us18.api.mailchimp.com/3.0/lists/0243b2d7a3/members";
const options={
  method:"POST",
  auth:"john:be1fa777676767686835387837-us20"
}

const request=https.request(url, options,function(response){
  response.on("data",function(data){
    console.log(JSON.parse(data));
  });
  request.write(jsonData);
  req.end();
});

//console.log(firstName + " ....... " + lastName + " ......  " + email);

});

//api key
//be1fa777676767686835387837-us20

//list // ID
//0243b2d7a3

app.listen(3000,function(){
console.log("server is running on port 3000");
});
html,
body {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  padding-top: 40px;
  padding-bottom: 40px;
  background-color: #f5f5f5;
}

.form-signin {
  width: 100%;
  max-width: 330px;
  padding: 15px;
  margin: auto;
}

.form-signin .checkbox {
  font-weight: 400;
}

.form-signin .form-floating:focus-within {
  z-index: 2;
}

.middle{
  border-radius: 0;
  margin-bottom:-1px;
}

.top {
  margin-bottom: -1px;
  border-bottom-right-radius: 0;
  border-bottom-left-radius: 0;
}

.bottom{
  margin-bottom: 10px;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.88.1">
    <title>News letter sign up</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/5.1/examples/sign-in/">



    <!-- Bootstrap core CSS -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

    <!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/5.1/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/5.1/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/5.1/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/5.1/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/5.1/assets/img/favicons/safari-pinned-tab.svg" color="#7952b3">
<link rel="icon" href="/docs/5.1/assets/img/favicons/favicon.ico">
<meta name="theme-color" content="#7952b3">


    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }
    </style>


    <!-- Custom styles for this template -->
    <link href="css/style.css" rel="stylesheet">
  </head>
  <body class="text-center">

<main class="form-signin">
  <form action="/" method="POST">
    <img class="mb-4" src="Images/santa.png" alt="" width="72" height="57">
    <h1 class="h3 mb-3 fw-normal">Sign up to my newsletter</h1>

    <input type="text" name="fName" class="form-control top" placeholder="First Name" required autofocus>
      <input type="text" name="lName" class="form-control midle" placeholder="last Name" required>
      <input type="password" name="email" class="form-control bottom" placeholder="Email" required>


    <button class="w-100 btn btn-lg btn-primary" type="submit">Sign me up</button>
    <p class="mt-5 mb-3 text-muted">&copy; 2017–2021</p>
  </form>
</main>



  </body>
</html>

so, That was the code, I have to say that I am learning, and this from a course. It does not work me when I am trying to do it, and I would to understand why:

also this this what my terminal is saying: This is the what my terminal is complaining about

and I am connected localhost port 3000



Solution 1:[1]

Me too learning from same course and stuck with the same problem, then I went through the mailchimp api documentation and came up with the following code (it worked for me):

const express = require("express");
const bodyParser = require("body-parser");
const mailchimp = require("@mailchimp/mailchimp_marketing");

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

app.listen( 3000, () => {
    console.log("server is listening at 3000");
});

app.get("/", (req, res) => {
    res.sendFile(__dirname + "/signup.html");
});

app.post("/", (req, res) => {
    const fname = req.body.Fname;
    const lname = req.body.Lname;
    const email = req.body.email;

    mailchimp.setConfig({
        apiKey: "YOUR_API_KEY",
        server: "YOUR_SERVER_PREFIX",
    });

    const run = async () => {
        const response = await mailchimp.lists.batchListMembers("3230304ca4", {
            members: [
                {
                    email_address: email,
                    status: "subscribed",
                    merge_fields: {
                        FNAME: fname,
                        LNAME: lname,
                    },
                },
            ],
        });

        if (response.error_count) {
            res.sendFile(__dirname + "/failure.html");
        } else {
            res.sendFile(__dirname + "/success.html");
        }
    };

    run();
});

app.post("/failure", (req, res) => {
    res.redirect("/");
});

You need to install mailchimp library through npm by the following command

npm install @mailchimp/mailchimp_marketing

Have a look at example responses in the documentation sent by the mailchimp API if you have any errors.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jayanth