Research on updating Mailchimp members using nodejs http request

Here is the script for updating member's subscribe status.

const https = require('https');
const fs = require('fs');
const querystring = require('querystring')

const listId = '2c51d1ee79'
const subscriberHash = '8526a3835c5727b71ce1088f4e96da22' // md5 of '276489620@qq.com'

const postData = JSON.stringify({
    'status': 'unsubscribed'
})

const options = {
    hostname: 'us19.api.mailchimp.com',
    path: `/3.0/lists/${listId}/members/${subscriberHash}`,
    method: 'PATCH',
    headers: {
        'Authorization': 'Basic YOUR-TOKEN-HERE-us19',
        'Content-Type': 'application/json',
        'Content-Length': postData.length
    },
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);
    res.setEncoding('utf8');
    res.on('data', (chunk) => {
        console.log(`BODY: ${chunk}`);
    });
    res.on('end', () => {
        console.log('No more data in response.');
    });
});

req.on('error', (e) => {
    console.error(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();

I'm struggling with the error response of 411 in the beginning before I changed the following two snippet:

#1:

// Wrong, postData is 'status=unsubscribed'
const postData = querystring.stringify({
   'status': 'unsubscribed'
});

// Correct, postData is '{"status": "unsubscribed"}'
const postData = JSON.stringify({
    'status': 'unsubscribed'
})

#2:

// add 'Content-Length': postData.length in the headers
const options = {
    hostname: 'us19.api.mailchimp.com',
    path: `/3.0/lists/${listId}/members/${subscriberHash}`,
    method: 'PATCH',
    headers: {
        'Authorization': 'Basic YOUR-TOKEN-HERE-us19',
        'Content-Type': 'application/json',
        'Content-Length': postData.length // This is important. Without the request length, response of 411 Bad Request will be got.
    },
};

Then I saw the member 276489620@qq.com's status turned from subscribed to unsubscribed in Mailchimp's admin page.

image.png

So the next updating(the data from postgresql) would be as easy as this.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,486评论 0 10
  • 新的一年开学,臭小子适应得还算不错。三周的休假,我还担心会退步,还好没有,现在上下课跟老师打招呼环节基本可以独立啦...
    还记得坚持阅读 203评论 0 0