2

I am trying to make a sign-up form by which when a user enters his first name, second name and email in that form, he will be signed in and I can see his name and email in the audiences section of Mailchimp.

After finishing up my code (almost), I tried to execute it but nothing happened. It just kept loading so I went back to my code, copied the link by which I have my list-ID on and I use nodemon (a node package designed for auto-loading the terminal) which told me through the terminal as:

{
  type: 'https://mailchimp.com/developer/marketing/docs/errors/',
  title: 'API Key Invalid',
  status: 401,
  detail: "Your API key may be invalid, or you've attempted to access the wrong datacenter.",
  instance: 'c97f4b31-f9df-d2bc-6bb7-ab1a6ad5874b'
}

My HTML code:

<!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.87.0">
    <title>NewsLetter Sign-Up</title>

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



    <!-- Bootstrap core CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" 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="styles.css" rel="stylesheet">
</head>

<body class="text-center">


    <form action="/" class="form-signin" method="post">
        <img class="mb-4" src="images/gul code.png" alt="" width="72" height="57">

        <h1 class="h3 mb-3 fw-normal">Signup to My NewsLetter!</h1>

        <input type="text" name="fName" class="form-control top" id="floatingInput" placeholder="First Name" required autofocus>
        <input type="text" name="lName" class="form-control middle" id="floatingPassword" placeholder="Second Name" required>
        <input type="text" name="email" class="form-control bottom" id="floatingPassword" placeholder="E-mail" 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; YourCode</p>
    </form>

</body>

</html>

My styles.css for the HTML document:

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 .form-floating:focus-within {
    z-index: 2;
}

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

.middle {
    border-top-left-radius: 0;
    border-bottom-right-radius: 0;
}

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

And finally, my JavaScript:

const express = require("express");
const request = require("request");
const bodyParser = require("body-parser");
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_address: email,
            status: "subscribed",
            merge_fields: {
                FNAME: firstName,
                LNAME: lastName
            }
        }]
    };

    const jsonData = JSON.stringify(data);
    const url = "https://us5.api.mailchimp.com/3.0/lists/{list_id}";
    const options = {
        method: "POST", // here
        auth: "legion1:myapikey"
    }



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

    })

    request.write(jsonData);
    request.end();





});

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

I looked up many questions on the internet and within Stack Overflow, but none of which fixes this error. There were many Stack Overflow questions which did not work for me.

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 1
    Is your `url` valid? It looks like `{list_id}` is just a string instead of ``https://us6.api.mailchimp.com/3.0/lists/${list_id}`` and I don't see `list_id` variable in your code. – Veter Aug 11 '21 at 10:16
  • 1
    I used the word List_id instead of my actual id and for ```https://us6.api.mailchimp.com/3.0/lists/${list_id}```, it gives the error detail: "Your API key may be invalid, or you've attempted to access the wrong datacenter.",```. –  Aug 11 '21 at 10:21
  • try adding this one to your options: `headers: { 'Authorization': 'Bearer ' } ` – Veter Aug 11 '21 at 10:24
  • I tried adding that to my options but now I get a "403" error in which the details say ```"The API key provided is linked to datacenter 'us5>'",```. What does this mean?? All I do know is that it doesn't recognize me as an authorized user. –  Aug 11 '21 at 12:15
  • maybe this can help you? https://stackoverflow.com/a/41888321/9618749 – Veter Aug 11 '21 at 15:23

2 Answers2

1

I think you have used wrong API, instead of using "Your API keys" you might have used "Your Mobile SDK Client keys" on mailchimp. Another thing is you need to make this correct.const data={ members: [{ email_address:email, status: "subscribed", merge_fields:{ FNAME: firstName, LNAME: lastName, } }] };

0

Maybe I'm too late to help you, but I'm doing the same course as you (Dr. Angela Yu - Full-Stack Web Developer Bootcamp) and this is my code:

const express = require("express")
const mailchimp = require("@mailchimp/mailchimp_marketing")
const app = express()
const https = require("https")


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

//Setting up MailChimp

mailchimp.setConfig({
//API KEY
 apiKey: "xxxxxxxxxxxxxxxxxxxxxx-usxx",
//API KEY PREFIX (THE SERVER)
  server: "usxx"
})

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

  //console.log(firstName, lastName, email);

  const data = {
    members: [{
        email_address: email,
        status: "subscribed",
        merge_fields: {
          FNAME: firstName,
          LNAME: lastName}
      }]
  }

  const jsonData = JSON.stringify(data)
  
  const url = "https://usxx.api.mailchimp.com/3.0/lists/(**YOUR LIST ID HERE**)"
  
  const options = {
    method: "POST",
    auth:'anyStringYouWant:xxxxxxxxxxxxxxx-usxx' 
    //Enter the API key
  }
  
  const request = https.request(url, options, function(response) {
    if (response.statusCode === 200) {
      res.sendFile(__dirname + "/success.html")
    } else {
      res.sendFile(__dirname + "/failure.html")
    }

    response.on("data", function (data){
      console.log(JSON.parse(data))
        })
      })

      //comment the request to test the de failure page
      request.write(jsonData)
      request.end()

    })

app.post("/failure", function (req, res) {
  res.redirect("/")
})

app.listen(3000, () => console.log("Server is running on port 3000"))

With this code it doesn't show any error on the terminal and enter a new contact to the mailchimp list.