简体   繁体   English

从nodejs向客户端发送数据不起作用

[英]sending data from nodejs to client not working

I am trying to send a status message to client via ajax call using GET method. 我正在尝试使用GET方法通过ajax调用向客户端发送状态消息。 My data to Nodejs server goes through fine, but i cannot send back the data to my client.I am using expressjs as my framework. 我到Nodejs服务器的数据运行良好,但是我无法将数据发送回客户端。我使用expressjs作为框架。 I know the data exists because when I console.log(error) I get a object such as {[Error:test@test.com is already subsribed]} but i cannot output this message to client. 我知道数据存在,因为当我console.log(error)时,我得到了一个对象,例如{[Error:test@test.com已经被添加]},但是我无法将此消息输出到客户端。

Here is the route.js: it captures (\\subscribe) on app.js 这是route.js:它在app.js上捕获(\\订阅)

function signUp(name, email){
    var MailChimpAPI = require('mailchimp').MailChimpAPI;
    var API_KEY = 'asdfasdf',
            LIST_ID = 'asdfasdfas';
  var api = new MailChimpAPI(API_KEY , { version : '1.3', secure : false });
    var names = name.split(' '), status;
    var data ={
            apikey: API_KEY,
            id: LIST_ID,
            email_address : email,
            merge_vars: {'FNAME': names[0], 'LNAME': names[1]},
            double_optin: false,
            send_welcome: true
        };

     api.listSubscribe(data, function(error) {

            if(error != null){
                console.log(error);
                status = error;
            }else {
            console.log('success');
                status= '{success}';
            }
        });

    return status;
}


exports.send = function(req, res, next){
    var name = req.query.name, email = req.query.email;
    res.writeHead(200, {"Content-Type": "json"});
    res.send(signUp(name, email));
    res.end();

}

Here is my client side: (returns null) 这是我的客户端:(返回null)

$.ajax({
    url:'subscribe',
    method: 'GET',
    data: {name: name, email: email},
    dataType: 'JSON',
    success: function(res){
    alert(res);
    }

I don't know the API (mailchimp) you're using, so the solution might be totally wrong. 我不知道您使用的API(mailchimp),因此解决方案可能完全错误。 But generally you can see the difference between synchronous and asynchronous programming. 但是通常您会看到同步和异步编程之间的区别。 Please read some tutorials to fully understand the Node.js way, because it takes some time to embrace this kind of programming :-) 请阅读一些教程以完全理解Node.js的方式,因为接受这种编程需要一些时间:-)

The most important thing is that functions typically don't return values, but call a callback-function (sometimes not named callback but done ) when they are ready or an error was encountered. 最重要的是,函数通常不返回值,而是在它们准备就绪或遇到错误时调用回调函数(有时未命名为callback而是done )。

function signUp(name, email, callback) { // <----- provide a callback
    var MailChimpAPI = require('mailchimp').MailChimpAPI;
    var API_KEY = 'asdfasdf',
        LIST_ID = 'asdfasdfas';
    var api = new MailChimpAPI(API_KEY, { version: '1.3', secure: false });
    var names = name.split(' '), status;
    var data = {
        apikey: API_KEY,
        id: LIST_ID,
        email_address: email,
        merge_vars: {'FNAME': names[0], 'LNAME': names[1]},
        double_optin: false,
        send_welcome: true
    };

    api.listSubscribe(data, function (error, result) {
        if (error) {
            console.log(error);
            callback(error); // <--- this is one of the "exit"-points of the function
        } else {
            console.log('success');
            callback(null, result); // <--- this is another
        }
    });
    // <----------- no return! nobody cares about the return value.
}


exports.send = function (req, res, next) {
    var name = req.query.name, email = req.query.email;
    res.writeHead(200, {"Content-Type": "json"});
    signUp(name, email, function (err, result) {

        // this function gets called when signUp is done (maybe seconds later)

        if (err) {
            res.send(500);
            return;
        }
        // don't know what the result looks like
        res.send({status: 'success'});
        // res.end(); DON'T USE res.end() in express!
    });
};

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

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