简体   繁体   中英

How can I read the status code of a mailchimp response?

I am playing around with the mailchimp API. The code snippet adds a user to a mailing list and afterwards a success or failure message should be displayed. Unfortunaley I can't get a grasp on the status code.. It seems I get a different response in the case of adding a user successfully or not. If it was successfully I can access the status via response.statusCode but that doesnt work in a case of a failure:

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

const app = express();
//Includes local/static files
app.use(express.static('public'));
// Ads body parser and the function to read posted data
app.use(bodyParser.urlencoded({extended: true}));

mailchimp.setConfig({
  apiKey: "XXX",
  server: "us10",
});


app.get('/', function(req, res){
  res.sendFile(__dirname+'/sign_up.html');
});

app.post('/', async function(req, res) {

  //Audience ID
  const listId = 'XXX'

  const response = await mailchimp.lists.addListMember(listId, {
  email_address: req.body.email,
  status: "subscribed",
  merge_fields: {
    FNAME: req.body.firstName,
    LNAME: req.body.lastName
  }
});

  console.log(response.statusCode);


  if (response.statusCode == 200) {
    res.send(response.statusCode);
  } else {
    res.send(response.statusCode);
  }
})

app.listen('3000', function() {
  console.log('Hello World');
})

By the way, why is mailchimp using an async function?

Thank you for your support!

Best, Matthias

You use an async keyword to make a function asynchronous.

async makes a function return a Promise

await makes a function wait for a Promise

Whenever you're using await in a function, you're supposed to make it asynchronous using async

I don't know if this is correct but it worked for me. I used the.then() method, you can learn more about it in the MDN docs

 async function addMember() { const response = await mailchimp.lists.addListMember(listID, { email_address: email, status: "subscribed", merge_fields: { FNAME: firstName, LNAME: lastName, } }).then( (value) => { console.log("Successfully added contact as an audience member."); res.sendFile(__dirname + "/success.html"); }, (reason) => { res.sendFile(__dirname + "/failure.html"); }, ); }

My code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM