现在我有一个这样的问题:我用node.js创建了一个服务器,服务器已经接收到了ajax request.With --从ajax接收到的数据,node.js向另一个服务器发送了一个post请求。现在我已经从另一台服务器获得了数据,主要问题是如何将数据发送回ajax,我尝试了许多方法,但它不起作用。
有人能在这个问题上帮我吗?
这是我的密码
====ajax请求
$.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
})
})使用post请求集创建用户id的====the api
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);
}发布于 2016-07-17 05:56:59
你的服务器代码。有http.createServer(function (req, res) {...}的那个
注意如何获得req和res参数?
因此,在event end,也就是在您收到评论“数据来自另一台服务器”的行之后,您可以这样做:
res.writeHead(/*HTTP_RESPONSE_CODE_FOR_AJAX_CLIENT=*/200);
res.end('Done');若要使用HTTP响应代码= 200向客户端发送响应,HTTP正文中的消息将“完成”。请注意,对于response对象,您可以做很多事情,您可能需要查看文档以获得更多信息。
见:
或(中文版)
中文快速解释:
req.on('end'...res对象在服务器的代码那里,你可以用打回给你的打回给你的客户端。
https://stackoverflow.com/questions/38417130
复制相似问题