繁体   English   中英

如何使用 Axios package 对 MailChimp api 进行发布请求

[英]How to do a post request to MailChimp api using Axios package

我最近开始使用Axios package。 我正在处理我的时事通讯注册页面,并使用它向MailChimp Api 发送新订阅者的 Post 请求,但出现400错误。 任何人都可以帮助我使用此代码。

var Data = {
    members: [{
        email_address: email,
        status: "suscribed",
        merge_fields: {
            FNAME: firstName,
            LNAME: lastName
        }
    }]
};

var jsonData=JSON.stringify(Data);  
axios.post(
        "https://***.api.mailchimp.com/3.0/lists/**********",{
            data: jsonData
        },
        {
            auth: {
                username: "any_name",
                password:"API_keys"
            }
        })

    .then(function(response) {
        console.log(response);
    })
    .catch(function(error) {
        console.log(error);
    });

用来自 npm 的 @mailchimp/mailchimp_marketing 代替 Axios,go,并且可以重现如下:

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

//Using body-parser
app.use(express.urlencoded({extended:true}));

//The public folder which holds the CSS
app.use(express.static("public"));

//Listening on port 3000 and if it goes well then logging a message saying that the server is running
app.listen(3000, function () {
console.log("Server is running at port 3000");
});

//Sending the signup.html file to the browser as soon as a request is made on localhost:3000
app.get("/", function (req, res) {
res.sendFile(__dirname + "/signup.html");
});

//Setting up MailChimp
mailchimp.setConfig({
apiKey: "YOUR API KEY-usX",
server: "usX"
});

//As soon as the sign in button is pressed execute this

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

//Add a contact to an audience
const listId = "YOUR AUDIENCE ID";
const subscribingUser = {
  firstName: firstName,
  lastName: lastName,
  email: email
};
//Uploading the data to the server
async function run() {
  const response = await mailchimp.lists.addListMember(listId, {
  email_address: subscribingUser.email,
  status: "subscribed",
  merge_fields: {
  FNAME: subscribingUser.fName,
  LNAME: subscribingUser.lName
  }
});
//If all goes well logging the contact's id
res.sendFile(__dirname + "/success.html")
console.log(`Successfully added contact as an audience member. The contact's id is ${response.id}.`);
}
//Running the function and catching the errors (if any)

  run().catch(e => res.sendFile(__dirname + "/failure.html"));
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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