简体   繁体   English

POST函数运行两次,第一次API调用失败,第二次运行。

[英]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. 我有一个订阅对话框,该对话框接受电子邮件地址,然后将其插入Mailchimp。

Its throwing errors out that make the experience not great. 它抛出的错误使体验不佳。 Upon further investigation it looks like the POST is being run twice. 经过进一步调查,似乎POST运行了两次。

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. 第一次运行api调用总是失败,但是随后再次运行并且可以正常工作,并且电子邮件已放入数据库中。

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. 我试图找到问题,因为因为它运行两次,所以AJAX函数总是会触发一个错误,这意味着我无法基于该函数的成功执行操作(下面的变量subscribeissuccess的要点)。

Any help would be greatly appreciated. 任何帮助将不胜感激。

The ajax function: Ajax函数:

 $.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: API插入/ 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' '... 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. 当根据@barmar和@Xeren Narcy的建议采取行动时,我发现我有两个事件处理程序,每个事件处理程序都在运行subscription函数。 One in the HTML form and one in jquery.main.js, when I removed one the problem went away. 当我删除一个时,HTML形式的一个和jquery.main.js中的一个就消失了。

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

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