neo neo - 4 months ago 40
Ajax Question

About node.js return data to ajax call function


Now I have a question like this:
I created a server with node.js ,and the server have receive a ajax request.With the data received from ajax ,node.js send a post request to another server. Now I have got the data from another server and the main question is how to send the data back to ajax, I have tried many ways but it does not work.


Can somebody help me on this issue?


here is my code


====ajax request

$.ajax({
type: "POST",
url: 'http://localhost:8888', // 这里要改成服务器的地址
data: userData,
success: function (data) {
console.log(data);
}
})


====

http.createServer(function (req, res) {
if (req.url == '/') {
var data = '';
var imdata;
util.log(util.inspect(req));
util.log('Request recieved: \nmethod: ' + req.method + '\nurl: ' + req.url);
req.on('data', function (chunk) {
imdata = querystring.parse(data += chunk);//转成对象的格式
})
req.on('end', function () {
var myIm = new ServerApi('e782429e48cb99f44b9c5effe414ac72', 'b88b9f2a2f74');
myIm.createUserId(imdata, function (err, data) {
//createUesrId is a api to deal with post request
console.log(data);//the data have received from another server,and now i do not know how to return the data to ajax success function

})
})


====the api to create user id with post requeset

ServerApi.prototype.postDataHttps = function (url, data, callback) {
this.checkSumBuilder();

var urlObj = urlParser.parse(url);
var httpHeader = {
'AppKey': this.AppKey,
'Nonce': this.Nonce,
'CurTime': this.CurTime,
'CheckSum': this.CheckSum,
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'Content-Length': Buffer.byteLength(data)
};
var options = {
hostname: urlObj.hostname,
port: 80,
path: urlObj.path,
method: 'POST',
headers: httpHeader
};
var that = this;
var req = http.request(options, function (res) {

res.setEncoding('utf8');
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);

res.on('data', function (chunk) {
if (Object.prototype.toString.call(callback) === '[object Function]') {
var result = JSON.parse(chunk);

callback.call(that, null, result);
return result;
}
});
});

var postData = querystring.stringify(data);
req.write(postData);
req.end(data);

req.on('error', function (err) {
if (Object.prototype.toString.call(callback) === '[object Function]') {
callback.call(that, err, null);
}
});

}
ServerApi.prototype.createUserId = function (data, callback) {
var url = 'https://api.netease.im/nimserver/user/create.action';
var postData = {
'accid': data['accid'] || '',
'name': data['name'] || '',
'props': data['props'] || '',
'icon': data['icon'] || '',
'token': data['token'] || ''
};
this.postDataHttps(url, postData, callback);
}

Answer

On your server code. The one with http.createServer(function (req, res) {...}

Notice how you got a req and res parameter?

So on event end, that is req.on('end' function... Right after the line where you got a comment saying the 'data is received from another server', you can do something like;

res.writeHead(/*HTTP_RESPONSE_CODE_FOR_AJAX_CLIENT=*/200);
res.end('Done');

to send a response back to your client with HTTP response code = 200 and the message in the HTTP body would be 'Done'. Note that, there are quite a number of things you can do with the response object, you may want to see the documentation for more information.

See:
https://nodejs.org/api/http.html#http_response_writehead_statuscode_statusmessage_headers

OR (中文版)

http://nodeapi.ucdok.com/api/http.html#http_class_http_serverresponse_7847

Quick explanation in Chinese:
在服务器的代码req.on('end'...那里, 你可以用resobject打回给你的AJax client.