我正在尝试编写一个基本的REST Post客户端来处理node.js,因为我必须使用REST API,我必须从响应中获取详细信息,包括使用cookie来维护我的REST会话的状态。服务器。我的问题是,当res.on触发PRINTME变量中的所有数据并将其返回到test.js console.log()时,从响应中提取json对象的最佳方法是什么。
var rest = require('./rest');
rest.request('http','google.com','/upload','data\n');
console.log('PRINTME='JSON.stringify(res.PRINTME));
exports.request = function (protocol, host, path, data, cookie){
var protocalTypes = {
http: {
module: require('http')
, port: '80'
}
, https: {
module: require('https')
, port: '443'
}
};
var protocolModule = protocalTypes[protocol].module;
var options = {
host: host,
port: protocalTypes[protocol].port,
path: path,
method: 'POST',
headers: {
'Content-Type': 'text/xml'
, 'Content-Length': Buffer.byteLength(data)
, 'Cookie': cookie||''
}
};
console.log('cookies sent= '+options.headers.Cookie)
var req = protocolModule.request(options, function(res) {
var PRINTME = res;
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
PRINTME.body = chunk;
console.log('BODY: ' + chunk);
});
res.on('close', function () {res.emit('end')});
});
req.on('error', function(e) {
console.error('Request Failure: ' + e.message);
});
req.write(data);
req.end();
};
答案 0 :(得分:1)
使用像request这样的软件包可以帮助您简化代码。
以下是rest.js
var request = require('request');
module.exports = function(protocol, host, path, data, cookie, done) {
var options = {
host: host,
port: protocalTypes[protocol].port,
path: path,
method: 'POST',
headers: {
'Content-Type': 'text/xml',
'Content-Length': Buffer.byteLength(data)
},
jar: true
};
request(options, function(err, resp, body) {
if (err) return done(err);
// call done, with first value being null to specify no errors occured
return done(null, resp, body);
});
}
将jar
设置为true
会记住Cookie以供将来使用。
有关可用选项的更多信息,请参阅此链接
https://github.com/mikeal/request#requestoptions-callback
在另一个档案中使用此功能
var rest = require('./rest');
rest(... , function(err, resp, body){
...
});