我正在尝试使用GET方法通过ajax调用向客户端发送状态消息。 我的Nodejs服务器的数据很好,但我无法将数据发送回我的客户端。我使用expressjs作为我的框架。 我知道数据存在,因为当我在console.log(错误)时,我得到了一个对象,例如 {[错误:test@test.com已经被包含]}但我无法将此消息输出到客户端。
这是route.js:它在app.js上捕获(\ subscribe)
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();
}
这是我的客户端:(返回null)
$.ajax({
url:'subscribe',
method: 'GET',
data: {name: name, email: email},
dataType: 'JSON',
success: function(res){
alert(res);
}
答案 0 :(得分:0)
我不知道您正在使用的API(mailchimp),因此解决方案可能完全错误。但通常您可以看到同步和异步编程之间的区别。请阅读一些教程以完全理解Node.js的方式,因为它需要一些时间来接受这种编程: - )
最重要的是函数通常不返回值,但在它们准备好或遇到错误时调用回调函数(有时不是callback
而是done
)。 / p>
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!
});
};