【问题标题】:POST function runs twice, first time API call fails, second time it works.POST 函数运行两次,第一次 API 调用失败,第二次运行。
【发布时间】:2017-05-20 15:58:05
【问题描述】:

我有一个订阅对话框,它接收电子邮件地址,然后将其插入 Mailchimp。

它抛出的错误使体验不是很好。经过进一步调查,看起来 POST 正在运行两次。

第一次运行 api 调用总是失败,但随后它再次运行并正常工作,并且电子邮件被放入数据库中。

我正在尝试查找问题,因为由于它运行两次 AJAX 函数总是会触发错误,这意味着我无法根据函数成功执行操作(变量 subscribeissuccess 下面的点。

任何帮助将不胜感激。

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.');
        }
});

/subscribe 中的 API 插入:

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});
});
}; 

'...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();
}
};

我在成功添加电子邮件时遇到的错误:

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

【问题讨论】:

  • 我猜你在发送 AJAX 请求时并没有阻止默认表单提交。
  • 如果您发布表单 HTML 和事件代码,这将有助于确认 @Barmar 的意见(我同意)
  • 感谢您的建议!结果变得更简单了。当我在这里复制代码时,我注意到我有两个事件处理程序运行订阅功能,一个在 HTML 表单中,一个在 jquery.main.js 中。我删除了 HTML 中的那个,不再有这个问题。
  • 嘿@KonradKopczynski,我的 PUT 请求仅使用相同的有效负载触发一次,但与您的情况类似,它第一次失败。有什么想法吗?

标签: javascript ajax node.js mailchimp


【解决方案1】:

根据@barmar 和@Xeren Narcy 的建议采取行动时,我发现我有两个事件处理程序,每个处理程序都在运行订阅函数。一个在 HTML 表单中,一个在 jquery.main.js 中,当我删除一个时,问题就消失了。

【讨论】:

    猜你喜欢
    • 2020-03-28
    • 2020-08-22
    • 1970-01-01
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    相关资源
    最近更新 更多