简体   繁体   中英

POST function runs twice, first time API call fails, second time it works.

I have a subscribe dialog that takes email address and then inserts it into Mailchimp.

Its throwing errors out that make the experience not great. Upon further investigation it looks like the POST is being run twice.

The first time it runs the api call always fails, but then it runs again and works and the email is put in the database.

I'm trying to find the problem because since it runs twice the AJAX function always triggers an error which means I can't do things based on the function being successful (the point of the variable subscribeissuccess below.

Any help would be greatly appreciated.

The ajax function:

 $.ajax({
        type: "POST",
        url: "/subscribe",
        data: data, 
        success: function(data){
            $("#subscribe-form2 :input").prop("disabled", false);
            if(data.success){

                subscribeissuccess = 'TRUE';

            }   else {
                $('#subscribe-message2').html('Error occurred during subscribe. Please try again later.');
            }
        }, error: function(){
            $("#subscribe-form2 :input").prop("disabled", false);
            $('#subscribe-message2').html('Error occurred during during subscribe. Please try again later.');
        }
});

The API insert in /subscribe:

module.exports = function(req, res){
var emailId = req.body.email;
var button = req.body.subscribe;
var api = require('../api');

var apikey = "removed";
var listid = "removed";

var body = JSON.stringify({apikey: apikey, id: listid, email: {'email': emailId}, merge_vars:{groupings:[{name:"MERGE1", groups:[button]}]}, double_optin: false, send_welcome: false}),
link = "/2.0/lists/subscribe.json";

api.call(link, body, function(data){
    try{
        var ret = JSON.parse(data);
        console.log(data);
        if(ret.leid && ret.euid) res.json({success: true});
        else if(ret.code && ret.code == 214) res.json({success: true});
        else res.json({success: false});
    } catch(e){
        res.json({success: false});
    }       
}, function(err){
    res.json({success: false});
});
}; 

The function at '...api'

module.exports = {
call: function (endpoint, body, callback, errcallback){
    var http = require('https');
    var options = {
        host: 'us5.api.mailchimp.com',
        post: 443,
        path: endpoint,
        headers: {
            "Content-Type": "application/json",
            "Content-Length": Buffer.byteLength(body),
            accept: '*/*'
        },
        method: 'POST'};

    var req = http.request(options, function(res){
        console.log('STATUS:' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        var data = '';
        res.on('data', function(chunk){
            data = data + chunk;
        });
        res.on('end', function(){
            callback(data);
        });
    });

    req.on('error', function(e){
        console.log('problem with request: ' + e.message);
        errcallback(e);
    });
    req.write(body);
    req.end();
}
};

The errors I get when a email is successfully added:

STATUS:500
HEADERS: {"server":"openresty","content-type":"application/json; charset=utf-8","content-length":"128","x-mailchimp-api-error-code":"-100","date":"Thu, 05 Jan 2017 22:59:51 GMT","connection":"close","set-cookie":["_AVESTA_ENVIRONMENT=prod; path=/"]}
{"status":"error","code":-100,"name":"ValidationError","error":"The email parameter should include an email, euid, or leid key"}
POST /subscribe 200 146ms - 17b
STATUS:200
HEADERS: {"server":"openresty","content-type":"application/json; charset=utf-8","content-length":"63","vary":"Accept-Encoding","date":"Thu, 05 Jan 2017 22:59:51 GMT","connection":"close","set-cookie":["_AVESTA_ENVIRONMENT=prod; path=/"]}
{"email":"ef@gmail.com","euid":"24d1d1b89e","leid":"118400873"}
POST /subscribe 200 277ms - 16b

When acting on suggestions from @barmar and @Xeren Narcy I discovered that I had two event handlers that were each running the subscribe function. One in the HTML form and one in jquery.main.js, when I removed one the problem went away.

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